1. 程式人生 > 其它 >SpringBoot 配置tk.mybatis 的異常問題

SpringBoot 配置tk.mybatis 的異常問題

SpringBoot 和 tk.mybatis

其餘的問題轉至https://blog.csdn.net/suzhenchao/article/details/8947108;

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

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<T> extends Mapper<T>, MySqlMapper<T>{
}

pom 檔案新增 Maven 的依賴 (同時要注意有沒有衝突)
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
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.<init>()

(這裡註解下)

比分說我的BaseDao包在這個路徑

@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;