1.问题描述
pojo类:
java
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@ToString
public class User {
private Integer id;
private String name;
private Integer age;
private String email;
public User(String name, Integer age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
}
Dao类:
java
@Mapper
public interface UserDao {
void insertBatch(@Param("users") List<User> users);
}
Mapper文件:
xml
<insert id="insertBatch" useGeneratedKeys="true"
keyProperty="id" parameterType="User">
INSERT INTO user (`name`, age, email) values
<foreach collection="users" item="item" separator="," >
(#{item.name,jdbcType=VARCHAR}, #{item.age,jdbcType=INTEGER}, #{item.email,jdbcType=VARCHAR})
</foreach>
</insert>
测试代码:
java
@Test
public void test_insertBatch(){
List<User> users = new ArrayList<User>(){{
User user = new User("sumAll",22,"sumAll@163.com");
User user2 = new User("sumAll2",20,"sumAll2@163.com");
}};
userDao.insertBatch(users);
logger.info(users.toString());
}
执行测试代码后,报以下错误:
org.springframework.jdbc.BadSqlGrammarException:
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 '' at line 1
The error may exist in file [xxx]
The error may involve com.sumAll.dao.UserDao.insertBatch-Inline
The error occurred while setting parameters
SQL: INSERT INTO user (name, age, email) values
大伙儿,发现哪里的问题导致了这个异常吗?
2.问题分析
观察测试代码发现,实例化的 user
并未添加进入 List
容器,导致 List
容器为空。
由于 List
为空, 最终生成的 SQL 语句变为 INSERT INTO user (name, age, email) values
,这就产生了 SQL 语法错误异常。
因此在使用批量插入语句之前,应当对集合进行判空处理。修改后的测试代码如下:
java
@Test
public void test_insertBatch(){
List<User> users = new ArrayList<User>(){{
User user = new User("sumAll",22,"sumAll@163.com");
User user2 = new User("sumAll2",20,"sumAll2@163.com");
add(user);
add(user2);
}};
if(!users.isEmpty()){
userDao.insertBatch(users);
logger.info(users.toString());
}
}
执行结果如下: