使用LambdaQueryWrapper 报错MybatisPlusException: can not find lambda cache for this property [****]

在使用Mockito进行MybatisPlus的Service层单元测试时,由于Mapper被mock,导致TableInfo无法初始化,进而引发Lambda查询异常。解决方案是在测试前手动调用TableInfoHelper.initTableInfo进行初始化。此问题的根本原因在于单元测试环境下,实体的TableInfo没有正常被缓存。
摘要由CSDN通过智能技术生成

目录

背景

问题

分析

原因

解决方案

深层次原因


背景

        进行单元测试编码时,使用了MybatisPlus,在对service层进行单元测试时,为保证数据与应用隔离,采用Mock的方式.

问题

        Mockito对Mapper进行mock后,相关的TableInfo信息无法初始化,导致Wrapper组装条件时
报:com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: can not find lambda cache for this property [****] of entity [Entity]

        我们在使用mybatisplus 时使用Lambda 表达式做查询条件会遇到mybatis拿不到缓存问题:
错误1:com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: can not find lambda cache for this entity
错误2:can not find lambda cache for this property [XXX] of entity [com.XXX.XXX]

分析

        排错时发现LambdaUtils.getColumnMap(aClass)中无数据;


原因

        首先是MybatisPlus的bug,经过分析后排除,再次考虑TableInfo的初始化过程被中止,或者被Mock替换了,更有可能是压根就没有触发。

        项目中使用JUnit & Mocktio进行单元测试,如果代码中使用LambdaQueryWrapper进行条件构造,在DO类中有类似@TableId、@TableLogic等注解,在执行单元测试时会报错 MybatisPlusException: can not find lambda cache for this property [] of entity []
问题:Mockito对Mapper进行mock后,相关的TableInfo信息无法初始化,导致Wrapper组装条件时
报:com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: can not find lambda cache for this property [****] of entity [Entity]
 

解决方案

        TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), “”), TeamWorkerSearch.class) 这一行就行,其中TeamWorkerSearch 是你要做条件的entity 对象

解决的方案是手动触发相关缓存信息收集(或许还有更优雅的方案)

在执行目标方法之前添加如下内容:

TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),Xxx.class);

假如一个test类里面使用到的方法多的话,可以使用before注解让这行代码在测试类中所有方法执行之前就添加。在junit 5.x中,@Before主键被@BeforeEach所替代。

 @BeforeEach
    public void initTable() {
        TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), Xxx.class);
    }

或者
 @Before
    public void init() {
        TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), Xxx.class);
    }

深层次原因

AbstractSqlInjector 会将所有 MapperBuilderAssistant 中的实体调用 initTableInfo

放到 TABLE_INFO_CACHE 这个map当中

 

 然后在使用 LambdaQueryWrapper 做查询条件拼接的时候

它又会从 TABLE_INFO_CACHE 这个map中取出来 

 

  • 14
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值