目录
1.2、批量 Insert Into插入记录后获得包含Id信息的记录信息
2.2、批量 Insert Into插入后获得包含Id的List
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、展现结果