Mybatis注解批量插入返回自动生成的id

背景

需要批量往A表中插入一批数据,之后返回插入的该批数据的主键。存入一个流水记录表B。

表结构

两个表结构
表A

CREATE TABLE `channel_link` (                                                                          
  `id` int(11) NOT NULL AUTO_INCREMENT,                                                                
  `channel_id` int(11) NOT NULL COMMENT '渠道id',                                                      
  `recruit_type` int(11) NOT NULL COMMENT,                                     
  PRIMARY KEY (`id`)                                                                                   
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='渠道链接'

表B

CREATE TABLE `channel_operate_history` (                                                      
  `id` int(11) NOT NULL AUTO_INCREMENT,                                                       
  `operate_target_type` int(11) NOT NULL COMMENT '操作对象',     
  `operate_target_record_id` int(11) NOT NULL COMMENT '操作对象具体根记录的id',                                         
  PRIMARY KEY (`id`)                                                                          
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='渠道操作记录'     

具体实现

参数出@Param中的名称要与mapper文件中,或者是Insert注解中的collection中的内容对应。

代码层
DAO

    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert({
            ""
    })
    int batchInsert(@Param("list") List<ChannelLink> channelLinks);

Service层

	List<ChannelLink> models = generateModels(param);
	//ids就是上一步批量插入之后返回的id.
	List<Integer> ids = models.foreach(model -> ids.add(model.getId());
	doSomethingsWithIds(ids);

参考资料

实践1:https://blog.csdn.net/shujukuss/article/details/79957827
github issue:https://github.com/mybatis/mybatis-3/pull/324

你可能感兴趣的:(MySQL)