1.问题描述
pojo类:
@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类:
@Mapper
public interface UserDao {
void insertBatch(@Param("users") List users);
}
Mapper文件:
INSERT INTO user (`name`, age, email) values
(#{item.name,jdbcType=VARCHAR}, #{item.age,jdbcType=INTEGER}, #{item.email,jdbcType=VARCHAR})
测试代码:
@Test
public void test_insertBatch(){
List users = new ArrayList(){{
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 语法错误异常。
因此在使用批量插入语句之前,应当对集合进行判空处理。修改后的测试代码如下:
@Test
public void test_insertBatch(){
List users = new ArrayList(){{
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());
}
}
执行结果如下: