springboot項目引入通用mapper(tk.mybatis.mapper)的時候一些可能會踩的坑


主要解決springboot項目引入通用mapper(tk.mybatis.mapper)的時候一些可能會踩的坑:諸如tk.mybatis.mapper.provider.base.BaseSelectProvider.()

java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class

 

  • 通用mapper
    import tk.mybatis.mapper.common.Mapper;
    import tk.mybatis.mapper.common.MySqlMapper;
    
    
    public interface BaseDao extends Mapper, MySqlMapper{
    }

     

  • pom 文件添加 Maven 的依賴 (同時要注意有沒有沖突)

     tk.mybatis
     mapper-spring-boot-starter
     2.0.0
  • yml配置加上通用mapper路徑(我的通用mapper叫BaseDao)
mapper:
    mappers: cn.hy.hyerp.erp.common.dal.BaseDao
    not-empty: false
    identity: mysql
  • 啟動類引入的@MapperScan 引入的是import tk.mybatis.spring.annotation.MapperScan;

啟動而不是import org.mybatis.spring.annotation.MapperScan;​​​​​​不然會報錯:

Cause: java.lang.InstantiationException: tk.mybatis.mapper.provider.base.BaseSelectProvider] with root cause
java.lang.NoSuchMethodException: tk.mybatis.mapper.provider.base.BaseSelectProvider.()

 

  • @MapperScan里的basePackage不能包含通用mapper(我的是BaseDao)的路徑,只包含其他的mapper的路徑,不然會報錯:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baseDao' defined in file [BaseDao.class]: Invocation of init method failed;

nested exception is tk.mybatis.mapper.MapperException: tk.mybatis.mapper.MapperException: java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class

 

  • 使用BaseDao的方法如果SQL語句報錯,注意在自己生成的entity里面加上@Table 和 @Column 標識entity對應的表名和字段名;通用mapper默認是將駝峰結構的字段轉化為下划線的結構,如調.selectAll()方法時,personType會默認轉為
    person_type,如果跟數據表的字段不對應會報錯。如我在數據表的字段名為personType時,加上注解就行。
        @Column(name = "personType")
        private Boolean personType;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM