MyBatis-Plus是一款MyBatis的加強工具(簡稱MP),爲簡化開發、提升效率,但咱們並無直接使用MP的CRUD接口,而是在原來的基礎上封裝一層通用代碼,單表繼承咱們的通用代碼,實現了單表的基礎get、save(插入/更新)、list、page、delete接口,使用Vo去接收、傳輸數據,實體負責與數據庫表映射。html
這樣作的目的是與咱們以前的那套jpa保持編碼風格上的一致,當咱們的通用接口不能知足要求時,應當先考慮使用MP的Service層CRUD接口,而後是Mapper的接口,最後纔是自定義查詢,本文將記錄實現過程mysql
MyBatis-Plus官網:https://baomidou.com/git
在咱們的工程裏新建子工程springboot-mybatis-plus,pom繼承父工程,引入Mybatis-Plus相關jar包github
<!--添加MyBatis-Plus依賴 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> <!--添加代碼生成器依賴 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.0</version> </dependency> <!-- 模板引擎 --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.0</version> </dependency>
啓動類中配置mapper掃描路徑spring
@SpringBootApplication @MapperScan("cn.huanzi.qch.springbootmybatisplus.*.mapper") public class SpringbootMybatisPlusApplication { public static void main(String[] args) { SpringApplication.run(SpringbootMybatisPlusApplication.class, args); } }
建立MybatisPlusConfig配置類sql
/** * MybatisPlusConfig配置類 */ @Configuration @ConditionalOnClass(value = {PaginationInterceptor.class}) public class MybatisPlusConfig { /** * 分頁插件相關 */ @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); return paginationInterceptor; } /** * 主鍵策略相關 */ @Bean public IKeyGenerator keyGenerator() { return new H2KeyGenerator(); } }
配置文件配置數據庫鏈接,與項目信息數據庫
server.port=10102 spring.application.name=springboot-mybatis-plus #修改thymeleaf訪問根路徑 spring.thymeleaf.prefix=classpath:/view/
ymlapache
spring: datasource: #數據庫相關 url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&characterEncoding=utf-8 username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver mvc: date-format: yyyy-MM-dd HH:mm:ss #mvc接收參數時對日期進行格式化 jackson: date-format: yyyy-MM-dd HH:mm:ss #jackson對響應回去的日期參數進行格式化 time-zone: GMT+8
到這裏項目簡單搭建完成後端
接下來就是通用代碼的編寫,咱們參考以前jpa的代碼,結合Mybatis-Plus的Mapper接口進行封裝通用get、save(插入/更新)、list、page、delete接口springboot
代碼佈局與jpa的風格一致
接口也同樣
MP原生的並不適合咱們,咱們要新建自定義模板,編寫代碼生成器
運行代碼生成器便可生成後端代碼,代碼風格與咱們以前的jpa高度一致,一樣是封裝一套通用CRUD、page分頁接口,單表繼承實現快速開發
get接口:http://localhost:10102/tbUser/get/2
list接口:http://localhost:10102/tbUser/list、http://localhost:10102/tbUser/list?id=2
page接口分頁、排序:http://localhost:10102/tbUser/page?page=1&rows=3&sidx=id&sord=desc
save有id,更新:http://localhost:10102/tbUser/save?id=2&username=huanzixxxx
save無id,新增:http://localhost:10102/tbUser/save?username=huanziyyy&password=000000&created=2020-08-16%2019:56:04
delete刪除:http://localhost:10102/tbUser/delete/14
至此,咱們便擁有了兩個編碼風格高度統一的ORM框架的自定義封裝,都有一套基礎通用的代碼、代碼自動生成工具,咱們的開發效率大大提升,無論後續項目須要用到那個ORM框架,咱們都有了技術儲備,實現快速開發!MyBatis相關可看回咱們以前的系列博客:SpringBoot系列——MyBatis整合
MP:SpringBoot系列——MyBatis-Plus整合封裝
JPA:SpringBoot系列——Spring-Data-JPA(究極進化版) 自動生成單表基礎增、刪、改、查接口
代碼已經開源、託管到個人GitHub、碼雲: