祝你前程似錦嚼酝,在初春浮还,在夏至,在秋末闽巩,在冬深
一钧舌、前言:
MyBatis是一款優(yōu)秀的持久層框架,它支持定制化SQL涎跨、存儲過程以及高級映射洼冻。MyBatis-Plus(簡稱 MP)是一個 MyBatis 的增強工具,在 MyBatis 的基礎(chǔ)上只做增強不做改變隅很,為簡化開發(fā)撞牢、提高效率而生。
二叔营、集成
在我們項目中屋彪,用到最多的ORM框架就是Mybatis了,但是相對于Mybtais绒尊,我們可以有一個更好的選擇:Mybatis-plus
1畜挥、依賴如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1.tmp</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2、對應(yīng)的數(shù)據(jù)庫表:
CREATE TABLE `tb_user` (
`id` bigint(20) NOT NULL,
`name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3垒酬、application配置
spring.datasource.url=jdbc:mysql:///spring-boot?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=password
logging.level.indi.zhaosheng.mybatis.plus.dao=debug
4砰嘁、數(shù)據(jù)庫表對應(yīng)的對象(這里稱為Po)
@TableName("tb_user")
@Setter
@Getter
public class UserPo {
private Long id;
private String name;
}
5件炉、DAO
public interface UserMapper extends BaseMapper<UserPo> {
}
6、Service
public interface UserService {
}
******************************************************************
@Service
public class UserServiceImpl implements UserService {
private IService<UserPo> userPoService;
public UserServiceImpl(UserMapper userMapper) {
this.userPoService = new BaseServiceImpl<>(userMapper, UserPo.class);
}
}
三矮湘、自定義
我們可以看到斟冕,在上面的Service里,通過構(gòu)造函數(shù)new了一個BaseServiceImpl的userPoService缅阳;在MybatisPlus里磕蛇,普通情況是每個Po都會有個Service繼承ServiceImpl的,這樣去操作ServiceImpl提供的batch方法時十办,就可以獲取到操作的對象的類型秀撇。這里做了一個簡化,即通過泛型構(gòu)造PoService向族。
public class BaseServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> {
/**
* <p>
* 這里繼承了mp提供的一個ServiceImpl類呵燕,
* 通過CodeGenerator生成的代碼里,
* 每個Po(即與數(shù)據(jù)庫表映射的對象)都會生成一個泛型為Po的Service件相,
* 這個Service的作用是確定ServiceImpl操作的對象類型再扭,
* 個人感覺沒有必要,可以通過下面的方式指定對象類型夜矗,
* 不指定的話泛范,batch操作會拋異常(Error: Cannot execute table Method, ClassGenricType not found .),
* 找不到對應(yīng)的對象類型
* 使用示例見{@link indi.zhaosheng.mybatis.plus.service.impl.UserServiceImpl#UserServiceImpl(UserMapper)}
* </p>
*
* @param mapper
* @param clz
* @return
* @auther muluo
*/
public BaseServiceImpl(M mapper, Class<T> clz) {
this.baseMapper = mapper;
this.entityClass = clz;
}
}
好了紊撕,以上就是SpringBoot集成MybatisPlus的全部內(nèi)容了罢荡,很簡單,單可用对扶。涉及到的具體的操作并沒有在這里列出來区赵,因為官網(wǎng)上已經(jīng)有了很多的示例了。準(zhǔn)備下次肝一下MP的具體操作的流程辩稽,梳理清楚里面的邏輯惧笛,以及具體的sql是如何生成的。