项目场景:
需要新建一个数据组,并在新建数据组的时候挑选已经在数据库中的组员,将组员分配到数据组里,将数据组的id和组员的id写入数据库的一个表中。
问题描述
1.在新建项目的时候选择组员会调用以
下方法,将数据组的id和组员id的集合传入
private void setByGroudAndItem(Integer id, Integer[] checkitemIds) {
if (checkitemIds==null){
throw new RuntimeException("参数错误");
}
for (Integer checkitemId : checkitemIds) {
HashMap<String, Integer> map = new HashMap<>();
map.put("checkgroup_id",id);
map.put("checkitem_id",checkitemId);
checkgroupMapper.setByGroudAndItem(map);
}
}
2.之后采用insert方法往数据库中的数据组表和数据组id和员工id表插入数据
<insert id="add" parameterType="com.health.pojo.Checkgroup">
insert into t_checkgroup(code,name,sex,helpCode,remark,attention)
values
(#{code},#{name},#{sex},#{helpCode},#{remark},#{attention})
</insert>
@Select("select checkitem_id from t_checkgroup_checkitem where checkgroup_id = #{id}")
List<Integer> findCheckItemIdsByCheckGroupId(Integer id);
3.会显示无法找到新建数据组的id
org.springframework.dao.DataIntegrityViolationException:
### Error updating database. Cause: java.sql.SQLIntegrityConstraintViolationException: Column 'checkgroup_id' cannot be null
原因分析:
因为在新建数据组的时候并没有传id值进去,在数据库中id是自增的主键,所以导致录入t_checkgroup_checkitem数据表的时候无法得到新建数据组的id。
解决方案:
在add新建方法中使用SELECT LAST_INSERT_ID()注解。
<selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
SELECT LAST_INSERT_ID()
</selectKey><insert id="add" parameterType="com.health.pojo.Checkgroup"> <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id"> SELECT LAST_INSERT_ID() </selectKey> insert into t_checkgroup(code,name,sex,helpCode,remark,attention) values (#{code},#{name},#{sex},#{helpCode},#{remark},#{attention}) </insert>
该注解主要用于新增数据的时候主键不能自动生成的问题,可以将插入数据的主键返回到user 对象中。
SELECT LAST_INSERT_ID()是得到insert数据的主键,该语句只支持自增主键。
keyProperty="id"是将得到的主键设置为id属性。
order="AFTER"是该语句将在执行完insert语句后执行。