Mybatis 返回List类型数据及Insert Into批量增加记录后返回带有Id的List

目录

1、使用场景

  1.1、返回List的使用场景

  1.2、批量 Insert Into插入记录后获得包含Id信息的记录信息

2、代码实现

2.1 返回List的实现

2.2、批量 Insert Into插入后获得包含Id的List

3、展现结果

4、参考和引用文章


1、使用场景

  1.1、返回List的使用场景

          在给前端页面或者app返回已经选择ids List。或者后端用于In 查询语句等等

  1.2、批量 Insert Into插入记录后获得包含Id信息的记录信息

         批处理插入记录后返回给后端,继续处理后续相关的业务,比如存储相关的关系记录表时候需要新生成的id。如最近项目之中使用,如果输入的是新的标签,需要先生成标签记录后返回标签的id,才能存储到标签与资源的关系表之中。  

2、代码实现

2.1 返回List的实现

   课程标签表(course_tag)表里一条课程id(course_id) 数据对应多条 tag_id数据,所以通过course_id查询出来的tag_id 是一个List。

mybatis代码如下:

//入参类型(Map)是String类型 courseId
<select id="getTagIdListByCourseId" parameterType="java.util.Map" resultType="java.lang.Long" >
    select tag_id
    from course_tag
    where course_id = #{courseId,jdbcType=VARCHAR}
</select>

2.2、批量 Insert Into插入后获得包含Id的List

	/**
	 *批量添加资源标签到标签表之中
	 * @param tagList
	 * @return
	 */
	int addBatchEnclosureTagList(List<Map<String, Object>> tagList);

//3.1 新增标签表(tag)之中没有 执行添加到标签表之中
if(newTagInfoList.size()>0) {
	List<Map<String, Object>> newAddEnclosureTagList=addBatchEnclosureTagList(newTagInfoList);
	//保存完毕后 获得把新增的标签添加需要存储 标签与资源关系的list之中
	for (int m = 0; m <newAddEnclosureTagList.size(); m++) {
		addResourceTagList.add(newAddEnclosureTagList.get(m));
	}
}			
//3.2 新增完毕标签后 获得相关的新增标签 添加关联关系表之中		
//循环获得资源对应的标签id 并存储到资源标签关联关系表之中(例如 3个标签 两个资源 需要写入6条关系数据)
List<CourseEnclosure> courseEnclosureUpdateList =new ArrayList<CourseEnclosure>();
courseEnclosureUpdateList.add(courseEnclosure);
if(addResourceTagList.size()>0) {
	addBatchEnclosureTagRelationList(user,courseEnclosureUpdateList, addResourceTagList);
}

   Mybatis 代码配置 其中如果要返回包含Id的list 必须配置一下两个关键参数 useGeneratedKeys="true" keyProperty="id"

   <!-- 批处理添加资源对应的标签记录 -->
   <insert id="addBatchEnclosureTagList" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id">
	   INSERT INTO tag 
	   (tag_descn,org_id,owner_company,creator_id,create_time,modify_id,modify_time) 
	   SELECT * from 
		<foreach collection="list" item="item" index="index" open="(" close=")" separator="union all">
		   (SELECT #{item.tagName} as tagName,#{item.orgId} as orgId,
		   #{item.ownerCompany} as ownerCompany,#{item.creatorId} as creatorId,
		   #{item.createTime} as createTime,#{item.modifyId} as modifyId,#{item.modifyTime} as modifyTime
		   FROM DUAL)
	   </foreach> b
	</insert>

3、展现结果

     

4、参考和引用文章

mybatis返回list类型数据  mybatis mysql 批量insert 返回主键

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值