mybatis批量插入返回自增长id集合
都知道使用useGeneratedKeys
可以在插入数据的返回自增长的id,其实在批量插入的时候也可以使用useGeneratedKeys
返回批量插入的自增长id集合
UserScoreDo.java
:
public class UserScoreDo implements Serializable {
private Integer id;
private Long userId;
private Integer score;
private Date createdAt;
// omit getter and setter
}
UserScoreDoMapper.java
:
public interface UserScoreDoMapper {
int insertBatchIds(List<UserScoreDo> list);
}
UserScoreDoMapper.xml
:
<insert id="insertBatchIds" useGeneratedKeys="true" keyProperty="id">
insert into t_user_score(user_id,score,created_at) values
<foreach collection="list" item="obj" separator=",">
(#{obj.userId}, #{obj.score}, now())
</foreach>
</insert>
测试:
@Test
public void insertBatchIds(){
List<UserScoreDo> userScoreDoList = new ArrayList<>();
Random random = new Random();
for (int i=0; i < 4; i++){
UserScoreDo userScoreDo = new UserScoreDo();
userScoreDo.setUserId(Long.valueOf(100+i));
userScoreDo.setScore(random.nextInt(100));
userScoreDoList.add(userScoreDo);
}
userScoreDoMapper.insertBatchIds(userScoreDoList);
System.out.println(JSON.toJSONString(userScoreDoList));
}
结果:
[{
"id": 1,
"score": 6,
"userId": 100
},
{
"id": 2,
"score": 1,
"userId": 101
},
{
"id": 3,
"score": 56,
"userId": 102
},
{
"id": 4,
"score": 36,
"userId": 103
}]
可以发现,自增长id就在传入的List中,mybatis已经给我们设置进去了