简单描述:做开发的时候,会遇到一次插入好多条记录,怎么做好呢?

解决思路:循环insert啊!  哪凉快那呆着去←!←  这样会增加数据库开销的,当然不能这么干了,要在sql上下功夫。看代码,一下就明白了

代码

private void saveRoleOrgRes(String resIds,OhSysPriRoleOrgVo roleOrgVo) throws Exception {  //service层代码
if(Tools.notEmpty(resIds)){
List<OhSysPriRoleOrg> list = new ArrayList<>();
String[] resIdArr = resIds.split(","); //剪切id字符串
for (String resId: resIdArr) {
OhSysPriRoleOrg roleOrg = new OhSysPriRoleOrg();
roleOrg.setRoleOrgId(UuidUtil.get32UUID());
roleOrg.setOrgId(roleOrgVo.getOrgId());
roleOrg.setResId(resId); //为每个对象的id赋值
roleOrg.setRoleId(roleOrgVo.getRoleId());
roleOrg.setPriOrgLevel(roleOrgVo.getOrgLevel());
list.add(roleOrg);
}
dao.save("XXXXRoleOrgMapper.insert",list);
}
}
mapper的sql:
<insert id="insert" parameterType="java.util.List">
insert into <include refid="tableName"></include>
(
<include refid="Field"></include>
) values
<foreach collection="list" item="item" index="index" separator=",">
(
<include refid="FieldValue"></include>
)  
</foreach>
</insert>
 <sql id="FieldValue">  
#{item.xxxOrgId},
#{item.xxxId},
#{item.xxId},
#{item.xxxLevel},
#{item.xxxParentId}
</sql>

总结:这就是sql语法灵活运用的表现啦,对list中的每个对象加上foreach循环,但是 要特别的注意,映射取值的时候里边一定要放item,否则的话会mybatis绑定异常

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'xxxId' not found.Available parameters are [ xxxId ,list ]。

05-11 17:57