lambdaQuery().one()報錯MybatisPlusException: Class must not be null

使用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();  
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容