void batchAdd(List<Photo> list);
<insert id="batchAdd" parameterType="java.util.List" keyProperty="id" useGeneratedKeys="true">
insert into
photo(bizid,cover,sort,url,name,remark,status,type,addtime,uptime)
values<foreach item="item" index="index" separator="," collection="list">
(#{item.bizid},#{item.cover},#{item.sort},#{item.url},#{item.name},#{item.remark},#{item.status},#{item.type},now(),now())
</foreach>
</insert>
报错
Error getting generated key or setting result to parameter object.
org.apache.ibatis.executor.ExecutorException: Error getting generated key or setting result to parameter object. Cause: org.apache.ibatis.binding.BindingException: Parameter 'id' not found. Available parameters are [list]
Caused by: org.apache.ibatis.binding.BindingException: Parameter 'id' not found. Available parameters are [list]
第2次代码
<insert id="batchAdd" parameterType="java.util.List">
<selectKey resultType="long" keyProperty="id" order="AFTER">
SELECT
LAST_INSERT_ID()
</selectKey>
insert into
photo(bizid,cover,sort,url,name,remark,status,type,addtime,uptime)
values<foreach item="item" index="index" separator="," collection="list">
(#{item.bizid},#{item.cover},#{item.sort},#{item.url},#{item.name},#{item.remark},#{item.status},#{item.type},now(),now())
</foreach>
</insert>
批量插入成功了,但是id是null
第3次代码
Map map = new HashMap();
map.put("list", toAddPhotoList);
void batchAdd2(Map map);
<insert id="batchAdd2" keyProperty="id" useGeneratedKeys="true">
insert into
photo(bizid,cover,sort,url,name,remark,status,type,addtime,uptime)
values<foreach item="item" index="index" separator="," collection="list">
(#{item.bizid},#{item.cover},#{item.sort},#{item.url},#{item.name},#{item.remark},#{item.status},#{item.type},now(),now())
</foreach>
</insert>
批量插入成功了,但是id是null
在解决这个问题的过程中,我最初想实现“批量插入即可,心里默认为和插入1个一样,会有id”,
后来为了“批量插入也要返回主键id”,最后我发现,"这是不能实现的"。
mysql底层,insert values批量插入,返回的是“个数”。
目前,不知道怎么去证实我的猜测。
最后,附上单个插入的sql
<insert id="add" keyProperty="id" useGeneratedKeys="true">
insert into photo(bizid,cover,sort,url,name,remark,status,type,addtime,uptime)
values(#{bizid},#{cover},#{sort},#{url},#{name},#{remark},#{status},#{type},now(),now())
</insert>