MybatisPlus内置CRUD sql执行错误通用排查方法
这里拿IService接口的listByIds方法举例,传入了一个length为0的ArrayList,然后抛出了sql语法错误。
版本
<dependency>
<!--mybatis-plus3.3.2中 自带mybatis3.4.6 和mybatis-spring2.0.4-->
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.3.2</version>
</dependency>
Sql异常
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
at 略...
at com.baomidou.mybatisplus.extension.service.IService.listByIds(IService.java:206)
at 略...
IService.java
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表
*/
default List<T> listByIds(Collection<? extends Serializable> idList) {
return getBaseMapper().selectBatchIds(idList);
}
IService的listByIds方法返回的是BaseMapper selectBatchIds的执行结果,那么继续往下索引。
BaseMapper.java
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
可以看到这里作者已经写好注释,不能传入null或者空对象进行查询。那么为什么不能用呢,mybatisplus使用了java反射机制,动态注入方法,这里已经无法继续往下索引,通过全局定位直达SelectBatchByIds.Java,揭开神秘面纱。
SelectBatchByIds.java
坐标:com.baomidou.mybatisplus.core.injector.methods
/**
* 根据ID集合,批量查询数据
*
* @author hubin
* @since 2018-04-06
*/
public class SelectBatchByIds extends AbstractMethod {
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
SqlMethod sqlMethod = SqlMethod.SELECT_BATCH_BY_IDS;
SqlSource sqlSource = languageDriver.createSqlSource(configuration, String.format(sqlMethod.getSql(),
sqlSelectColumns(tableInfo, false), tableInfo.getTableName(), tableInfo.getKeyColumn(),
SqlScriptUtils.convertForeach("#{item}", COLLECTION, null, "item", COMMA),
tableInfo.getLogicDeleteSql(true, true)), Object.class);
return addSelectMappedStatementForTable(mapperClass, getMethod(sqlMethod), sqlSource, tableInfo);
}
}
可以看到,获取了一个sql语句,然后进行了一大堆文本操作,生成了mybatis mapper XML文件中那样的sql形式,然后再由原生mybatis的languageDriver创建BoundSql并负责执行,至此,整个流程一目了然。
SqlMethod.Java
public enum SqlMethod {
/**
* 查询
*/
SELECT_BATCH_BY_IDS("selectBatchIds", "根据ID集合,批量查询数据", "<script>SELECT %s FROM %s WHERE %s IN (%s) %s</script>"),
}
selectBatchIds的sql使用的是where in 条件,如果in的参数为空,数据库就会报错You have an error in your SQL syntax,也就顺理成章了。
标题:MybatisPlus内置CRUD方法sql执行错误通用排查方法
分类:MybatisPlus
链接:https://www.aqwdzy.com/content/91
版权:通天技术网(www.aqwdzy.com)所分享发布内容,部分为网络转载,如有侵权请立即联系方式,我们第一时间删除并致歉!
热烈庆祝通天技术网开业大吉
@通天技术网 热烈庆祝通天技术网开业大吉
热烈庆祝通天技术网开业大吉
@通天技术网 热烈庆祝通天技术网开业大吉