Mybatis中 通过foreach 批量插入实体类信息的一个注意点

it2025-05-24  11

mybatis通过foreach 批量插入实体类信息时:

在 foreach中最后一个#{} 不要带逗号 <insert id="addUsers"> insert into kunda_user (userCode,userName,userPassword,gender,birthday,phone,address,userRole) values <foreach collection="list" item="users" separator=","> ( #{users.userCode}, #{users.userName}, #{users.userPassword}, #{users.gender}, #{users.birthday}, #{users.phone}, #{users.address}, #{users.userRole} ) </foreach> </insert>

否则会报

Error updating database. Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')

生成的部分sql就为

values ( ?, ?, ?, ?, ?, ?, ?, ?, ) , (

 

2.因为dao层接口返回值类型为 List,所以 collection设置为 list  ;如果是数组则设置为array;如果是map则设置为map的key /** *批量插入用户信息 * @param users * @return int */ int addUsers (List<KunDaUser> users); 3 .item 是集合使用时的别名,可以设置为和#{ }中一致的名称。open是foreach的开始符号,separator是foreach的分割符号close是foreach的结束符号 <select id="getUserWithUserRoleRange" resultType="com.kunda.entity.KunDaUser"> select * from kunda_user where kunda_user.userRole in <foreach collection="array" item="userRoles" open="(" separator="," close=")"> #{userRoles} </foreach> </select>

 

最新回复(0)