使用MybatisPlus的lambdaQuery().one()查詢時,如果查詢結(jié)果不存在,那么就會報錯:
com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: Class must not be null
at com.baomidou.mybatisplus.core.toolkit.ExceptionUtils.mpe(ExceptionUtils.java:49) ~[mybatis-plus-core-3.5.3.jar:3.5.3]
at com.baomidou.mybatisplus.core.toolkit.Assert.isTrue(Assert.java:38) ~[mybatis-plus-core-3.5.3.jar:3.5.3]
at com.baomidou.mybatisplus.core.toolkit.Assert.notNull(Assert.java:72) ~[mybatis-plus-core-3.5.3.jar:3.5.3]
at com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils.currentSessionFactory(GlobalConfigUtils.java:53) ~[mybatis-plus-core-3.5.3.jar:3.5.3]
at com.baomidou.mybatisplus.extension.toolkit.SqlHelper.sqlSession(SqlHelper.java:86) ~[mybatis-plus-extension-3.5.3.jar:3.5.3]
at com.baomidou.mybatisplus.extension.toolkit.SqlHelper.execute(SqlHelper.java:301) ~[mybatis-plus-extension-3.5.3.jar:3.5.3]
解決辦法
將mybatis-plus-boot-starter版本升級到3.5.3.1
原因
IService接口的lambdaQuery()方法構(gòu)建一個LambdaQueryChainWrapper類的實(shí)現(xiàn)對象并返回用于后面的鏈?zhǔn)秸{(diào)用,而這里構(gòu)建LambdaQueryChainWrapper類對象時使用的是LambdaQueryChainWrapper(BaseMapper<T> baseMapper, Class<T> entityClass)這個構(gòu)造方法,這個方法并沒有給當(dāng)前類的成員變量entityClass賦值:
public LambdaQueryChainWrapper(BaseMapper<T> baseMapper, Class<T> entityClass) {
super();
this.baseMapper = baseMapper;
super.wrapperChildren = new LambdaQueryWrapper<>(entityClass);
}
接下來看鏈?zhǔn)秸{(diào)用的one()方法,這個方法會執(zhí)行ChainWrapper接口的默認(rèn)方法execute(SFunction<BaseMapper<T>, R> function),這個方法在執(zhí)行傳入進(jìn)來的function函數(shù),這個函數(shù)就是mapper.selectOne(getWrapper()),當(dāng)這個函數(shù)執(zhí)行的結(jié)果為null時,這里就會執(zhí)行orElseGet后面的部分:
default <R> R execute(SFunction<BaseMapper<T>, R> function) {
return Optional.ofNullable(getBaseMapper()).map(function).orElseGet(() -> SqlHelper.execute(getEntityClass(), function));
}
而在后面這個部分中會執(zhí)行getEntityClass()這個函數(shù),在這里這個函數(shù)的實(shí)現(xiàn)是由LambdaQueryChainWrapper類來實(shí)現(xiàn)的:
@Override
public Class<T> getEntityClass() {
return entityClass;
}
可以看到這個實(shí)現(xiàn)就是直接返回了LambdaQueryChainWrapper類的成員變量entityClass,而這個變量在我們前面講到的構(gòu)建LambdaQueryChainWrapper類對象過程中是沒有賦值的,所以導(dǎo)致后面在使用這個值時報了MybatisPlusException: Class must not be null異常,而在3.5.3.1版本中LambdaQueryChainWrapper類的getEntityClass()函數(shù)返回的是super.wrapperChildren.getEntityClass():
@Override
public Class<T> getEntityClass() {
return super.wrapperChildren.getEntityClass();
}