Mybatis-plus 自定义的sql 主键为null问题处理
文章目录
刚开始的代码是利用com.baomidou.mybatisplus.extension.service.IService 下的
@Transactional(rollbackFor = Exception.class)
default boolean saveBatch(Collection<T> entityList) {
return saveBatch(entityList, DEFAULT_BATCH_SIZE);
}方法执行的插入。后面改成批量插入,需要自己写sql。刚开始的sql为
// 设置useGeneratedKeys为true,返回数据库自动生成的记录主键id
<insert id="batchInsert" useGeneratedKeys="true" keyProperty="id">
insert into browse_log ( userId, browseTime,category,proId,productType)
VALUES
<foreach collection="list" item="item" index="index" separator=",">
(
#{item.userId},
#{item.browseTime},
#{item.category},
#{item.proId},
#{item.productType},
)
</foreach>
</insert>
类上主键也加了注解
@TableId(value = "Id", type = IdType.ASSIGN_ID)
private Long Id;可是执行下来却报错,说主键不能为null。
后来发现原因是自定义的insert sql内需要把id主键写进去。mybatis-plus的主键生成赋值是在插入的对象上的。
<insert id="batchInsert" useGeneratedKeys="true" keyProperty="id">
insert into browse_log ( Id,userId, browseTime,category,proId,productType)
VALUES
<foreach collection="list" item="item" index="index" separator=",">
(
#{item.id}
#{item.userId},
#{item.browseTime},
#{item.category},
#{item.proId},
#{item.productType},
)
</foreach>
</insert>修改之后插入成功。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论