MyBatis异常java.sql.SQLSyntaxErrorException的问题解决
作者:sumAll
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<User> users); }
Mapper文件:
<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>
测试代码:
@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 语法错误异常。
因此在使用批量插入语句之前,应当对集合进行判空处理。修改后的测试代码如下:
@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()); } }
执行结果如下:
到此这篇关于MyBatis异常java.sql.SQLSyntaxErrorException的问题解决的文章就介绍到这了,更多相关MyBatis java.sql.SQLSyntaxErrorException内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:
- MybatisPlus出现Error attempting to get column ‘xxx字段‘ from result set异常解决
- Mybatis操作数据时出现:java.sql.SQLSyntaxErrorException: Unknown column 'XXX' in 'field list'的问题解决
- MybatisPlusException:Failed to process,Error SQL异常报错的解决办法
- Mybatis配置错误:java.lang.ExceptionInInitializerError
- MybatisPlus BaseMapper 中的方法全部 Invalid bound statement (not found Error处理)
- 解决Mybatis出现报错Error querying database.Cause: java.lang.IndexOutOfBoundsException: Index 9 out of