0x0 背景
為了嘗試在mybatis框架下抽取BaseDao和BaseService着逐,使用tk mapper作為通用mapper對(duì)dao層通用操作進(jìn)行抽取呕童。
按照作者的介紹:
通用 Mapper4 是一個(gè)可以實(shí)現(xiàn)任意 MyBatis 通用方法的框架漆际,項(xiàng)目提供了常規(guī)的增刪改查操作以及Example 相關(guān)的單表操作。通用 Mapper 是為了解決 MyBatis 使用中 90% 的基本操作夺饲,使用它可以很方便的進(jìn)行開(kāi)發(fā)奸汇,可以節(jié)省開(kāi)發(fā)人員大量的時(shí)間。
0x1 抽取BaseDao和BaseService
這里我們使用Springboot項(xiàng)目進(jìn)行說(shuō)明往声,maven依賴如下:
<!-- 數(shù)據(jù)庫(kù)相關(guān)依賴 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>${tk.mybatis.version}</version>
</dependency>
springboot啟動(dòng)類:
@SpringBootApplication
@MapperScan(basePackages= {"com.fly.ship.hiker.user.dao"})
@EnableSwagger2
public class HikerApplication {
public static void main(String[] args) {
SpringApplication.run(HikerApplication.class, args);
}
}
1.1 首先是dao層抽壤拚摇:
public interface BaseDao<T> extends Mapper<T>, InsertListMapper<T> {}
其中Mapper包含了基本的增刪改查,例如:
insertSelective(t);
delete(t);
updateByPrimaryKey(t);
selectByPrimaryKey(id);
...
InsertListMapper則包含了批量插入:
@Options(useGeneratedKeys = true, keyProperty = "id")
@InsertProvider(type = SpecialProvider.class, method = "dynamicSQL")
int insertList(List<? extends T> recordList);
1.2 然后對(duì)service層抽取
代碼如下:
//接口:
public interface BaseService<T, Id> {
int save(T t);
int delete(T t);
int deleteById(Id id);
int update(T t);
T getById(Id id);
List<T> getAll();
int saveAll(List<T> list);
List<T> searchByExample(Example example);
}
//實(shí)現(xiàn)類
public abstract class BaseServiceImpl<T, Id> implements BaseService<T, Id> {
protected abstract BaseDao<T> getDao();
@Override
@Transactional
public int save(T t) {
return getDao().insertSelective(t);
}
@Override
@Transactional
public int saveAll(List<T> list) {
return getDao().insertList(list);
}
@Override
@Transactional
public int delete(T t) {
return getDao().delete(t);
}
@Override
@Transactional
public int deleteById(Id id) {
return getDao().deleteByPrimaryKey(id);
}
@Override
@Transactional
public int update(T t) {
return getDao().updateByPrimaryKey(t);
}
@Override
public T getById(Id id) {
return getDao().selectByPrimaryKey(id);
}
@Override
public List<T> getAll() {
return getDao().selectAll();
}
@Override
public List<T> searchByExample(Example example) {
return Collections.emptyList();
}
}
0x3 測(cè)試
我們做一個(gè)User類對(duì)應(yīng)于數(shù)據(jù)庫(kù)中的user表
@Table(name = "public.user")
public class User {
@Id
private Integer id;
private String username;
private String password;
private String name;
@Column(name = "nick_name")
private String nickName;
//省略getters&setters
}
做一個(gè)UserDao
@Repository
public interface UserDao extends BaseDao<User> {
}
做一個(gè)UserService
//接口
public interface UserService extends BaseService<User, Integer> {
}
//實(shí)現(xiàn)類烁挟,注意這里的繼承婴洼、實(shí)現(xiàn)寫(xiě)法
@Service
public class UserServiceImpl extends BaseServiceImpl<User, Integer> implements UserService {
@Autowired
private UserDao userDao;
@Override
protected BaseDao<User> getDao() {
return userDao;
}
}
最后來(lái)一個(gè)controller試下效果:
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@ApiOperation("測(cè)試")
@GetMapping("/hello/{name}")
public Result<String> hello(@PathVariable String name) {
return new Result<>(200, "success", "test");
}
@ApiOperation("添加用戶")
@PostMapping
public Result<Integer> saveUser(@RequestBody User user) {
int count = userService.save(user);
return new Result<>(200, "success", count);
}
}
啟動(dòng)后swagger界面:
保存一個(gè)用書(shū)試試,發(fā)現(xiàn)控制臺(tái)報(bào)錯(cuò):
java.lang.NoSuchMethodException: tk.mybatis.mapper.provider.base.BaseInsertProvider.<init>()
at java.lang.Class.getConstructor0(Class.java:3082) ~[na:1.8.0_171]
at java.lang.Class.newInstance(Class.java:412) ~[na:1.8.0_171]
at org.apache.ibatis.builder.annotation.ProviderSqlSource.invokeProviderMethod(ProviderSqlSource.java:165) ~[mybatis-3.4.6.jar:3.4.6]
at org.apache.ibatis.builder.annotation.ProviderSqlSource.createSqlSource(ProviderSqlSource.java:116) ~[mybatis-3.4.6.jar:3.4.6]
at org.apache.ibatis.builder.annotation.ProviderSqlSource.getBoundSql(ProviderSqlSource.java:102) ~[mybatis-3.4.6.jar:3.4.6]
at org.apache.ibatis.mapping.MappedStatement.getBoundSql(MappedStatement.java:292) ~[mybatis-3.4.6.jar:3.4.6]
at org.apache.ibatis.executor.statement.BaseStatementHandler.<init>(BaseStatementHandler.java:64) ~[mybatis-3.4.6.jar:3.4.6]
at org.apache.ibatis.executor.statement.PreparedStatementHandler.<init>(PreparedStatementHandler.java:40) ~[mybatis-3.4.6.jar:3.4.6]
......
百度一下撼嗓,發(fā)現(xiàn)是由于啟動(dòng)類中MapperScan要用tk自帶的柬采,修改如下:
import org.mybatis.spring.annotation.MapperScan;
改為
import tk.mybatis.spring.annotation.MapperScan;
緊接著又報(bào)錯(cuò):
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baseDao' defined in file [C:\Users\guoxiang6\IdeaProjects\ship\target\classes\com\fly\ship\hiker\base\dao\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
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1699) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:573) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
看起來(lái)baseDao不能被MapperScan掃描到,于是將
@MapperScan(basePackages= {"com.fly.ship.hiker.**.dao"})
改為具體
@MapperScan(basePackages= {"com.fly.ship.hiker.user.dao"})
這下就好了且警。