1. Mybatis-Plus簡介
1.1. 什么是Mybatis-Plus
MyBatis-Plus(簡稱 MP)是一個 MyBatis 的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。
1.2. 為什么要學習Mybatis-Plus
我們已經學習過Mybatis這個框架,我們只需要在dao層定義抽象接口,基於Mybatis零實現的特性,就可以實現對數據庫的crud操作。
如下兩個接口:
UserMapper接口
public interface UserMapper {
int deleteByPrimaryKey(Long id); int insert(User user); List<User> selectList(); User selectByPrimaryKey(Long id); } |
OrderMapper接口
public interface OrderMapper {
int deleteByPrimaryKey(Long id); int insert(Order order); List<Order> selectList(); User selectByPrimaryKey(Long id); } |
在上面兩個業務接口中,我們發現:它們定義了一組類似的crud方法。
在業務類型比較多的時候,我們需要重復的定義這組功能類似的接口方法。
如何解決這個問題呢?
使用Mybatis-plus工具,我們只需要將我們定義的抽象接口,繼承一個公用的BaseMapper<T>接口,就可以獲得一組通用的crud方法,來操作數據庫!!!
使用Mybatis-plus時,甚至都不需要任何的xml映射文件或者接口方法注解,真正的dao層零實現。
public interface OrderMapper extends BaseMapper<User> { //BaseMapper已經實現了通用的curd的方法了。如果有需要非通用的操作,才在這里自定義 } |
1.3. Mybatis-Plus小結
Mybatis-Plus只是在Mybatis的基礎上,實現了功能增強,讓開發更加簡潔高效。
Mybatis-Plus並沒有修改Mybatis的任何特性!!!
2. 入門示例
2.1. 需求
使用Mybatis-Plus實現對用戶的crud操作。
2.2. 配置步驟說明
(1)搭建環境(創建項目、導入包)
(2)配置Mybaits-Plus(基於Spring實現)
(3)編寫測試代碼
2.3. 配置步驟
2.3.1. 第一部分:搭建環境
2.3.1.1. 前提
已經創建好了數據庫環境:
CREATE TABLE `tb_user` ( `id` bigint(20) NOT NULL COMMENT '主鍵ID', `name` varchar(30) DEFAULT NULL COMMENT '姓名', `age` int(11) DEFAULT NULL COMMENT '年齡', `email` varchar(50) DEFAULT NULL COMMENT '郵箱', PRIMARY KEY (`id`) ) |
2.3.1.2. 說明
(1)Mybatis-Plus並沒有提供單獨的jar包,而是通過Maven(或者gradle)來管理jar依賴。本教程需要使用Maven構建項目。
(2)Mybatis-Plus是基於Spring框架實現的,因此使用Mybatis-Plus,必須導入Spring相關依賴。
2.3.1.3. 第一步:創建一個Maven項目
因為我們只是測試MybatisPlus框架,所以創建一個jar項目就可以了
|
2.3.1.4. 第二步:配置pom.xml構建文件
--需要導入依賴,並且配置項目的編碼,JDK版本等構建信息
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.chu.mybatisplus</groupId> <artifactId>mybatisplus-demo-01-start</artifactId> <version>1.0</version>
<!-- 依賴 --> <dependencies> <!-- spring依賴 -->
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.24.RELEASE</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.24.RELEASE</version> </dependency>
<!-- mybatis plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>2.3.3</version> </dependency>
<!-- mysql driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency>
</dependencies>
<!-- 只有配置了build標簽里面的內容,配置后都需要強制更新項目 --> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <!-- 設置編碼 --> <encoding>UTF-8</encoding> <!-- JDK版本 --> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <!-- 安裝install命令的時候跳過單元測試 -->
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.2</version> <configuration> <skipTests>true</skipTests> </configuration> </plugin> </plugins> </build> </project> |
2.3.2. 第二部分:配置整合部分
整合MybatisPlus與Spring的配置。創建一個spirng-data.xml配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 第一步:配置數據源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/mybatis-plus"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> <!-- 最大激活的連接數 --> <property name="maxActive" value="10"></property> <!-- 最大空閑連接數據 --> <!-- <property name="maxIdle" value="5"></property> --> <!-- 超時毫秒數 --> <property name="maxWait" value="30000"></property> </bean> <!-- 第二步:獲得會話工廠 --> <bean name="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean"> <!-- 指定數據源 --> <property name="dataSource" ref="dataSource"></property> </bean>
<!-- 第三步:掃描動態映射對象到Spring容器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 指定會話工廠 --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> <!-- 指定掃描的映射包 --> <property name="basePackage" value="org.chu.mybatisplus.mapper"></property> </bean>
<!-- 第四步:配置事務代理 --> <bean name="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <tx:annotation-driven transaction-manager="tx"/> </beans> |
2.3.3. 第三部分:實現操作功能
說明:完成實驗MybatisPlus對數據庫增刪改查。
2.3.3.1. 第一步:編寫POJO
說明:使用Mybatis-Plus不使用xml文件,而是基於一組注解來解決實體類和數據庫表的映射問題。
@TableName(value="tb_user") |
指定對應的表,表名和類名一致時,可以省略value屬性。 |
@TableId |
指定表的主鍵。Value屬性指定表的主鍵字段,和屬性名一致時,可以省略。Type指定主鍵的增長策略。 |
@TableField |
指定類的屬性映射的表字段,名稱一致時可以省略該注解。 |
package org.chu.mybatisplus.pojo;
import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableName; import com.baomidou.mybatisplus.enums.IdType;
@TableName(value="tb_user") public class User {
/*-- AUTO->`0`("數據庫ID自增") INPUT->`1`(用戶輸入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID") NONE-> 4 ("不需要ID") --*/ @TableId(value="id",type=IdType.AUTO) private Long id;//BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵ID', //如果屬性名與數據庫表的字段名相同可以不寫 @TableField(value="name") private String name;//VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名', @TableField(value="age") private Integer age;//INT(11) NULL DEFAULT NULL COMMENT '年齡', @TableField(value="email") private String email;//VARCHAR(50) NULL DEFAULT NULL COMMENT '郵箱', //補全get/set方法 }
|
2.3.3.2. 第二步:編寫Mapper接口
package org.chu.mybatisplus.mapper; import org.chu.mybatisplus.pojo.User; import com.baomidou.mybatisplus.mapper.BaseMapper; public interface UserMapper extends BaseMapper<User> {
} |
2.3.3.3. 第三步:測試增刪改查
package org.chu.test.mapper; import java.util.List;
import org.chu.mybatisplus.mapper.UserMapper; import org.chu.mybatisplus.pojo.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.mapper.Wrapper; //注意事項:Maven的單元測試包必須放置測試源碼包里面 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:spring-data.xml") public class UserMapperTest {
@Autowired private UserMapper userMapper;
@Test public void insert() { try { User user=new User(); user.setName("wangwu"); user.setAge(20); user.setEmail("wangwu@163.com"); Integer insert = userMapper.insert(user); System.out.println(insert); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Test public void deleteById() { try { Integer count = userMapper.deleteById(1L); System.out.println(count); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Test public void deleteByCondition() { try { //設置條件 EntityWrapper<User> wrapper=new EntityWrapper<>(); wrapper.like("name", "%wang%"); Integer count = userMapper.delete(wrapper); System.out.println(count); } catch (Exception e) { e.printStackTrace(); } }
@Test public void update() { User user=new User(); user.setName("wangwu"); user.setEmail("wangwu@163.com"); user.setId(2L); userMapper.updateById(user);
}
@Test public void findAll() { List<User> users = userMapper.selectList(null); for (User user : users) { System.out.println(user.getName()); } }
}
|
3. 常用配置
3.1. 實體類全局配置
如果在配置文件指定實體類的全局配置,那么可以不需要再配置實體類的關聯注解。
--配置文件spring-data.xml的修改
<!-- 第二步:獲得會話工廠 --> <bean name="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean"> <!-- 指定數據源 --> <property name="dataSource" ref="dataSource"></property> <!-- 全局實體類配置 --> <property name="globalConfig" > <bean class="com.baomidou.mybatisplus.entity.GlobalConfiguration"> <!-- AUTO->`0`("數據庫ID自增") INPUT->`1`(用戶輸入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID") --> <property name="idType" value="0"></property> <!-- 實體類名與表名的關聯規則是,忽略前綴 --> <property name="tablePrefix" value="tb_"></property> </bean> </property> </bean> |
--實體類就可以去掉關聯的注解了
package org.chu.mybatisplus.pojo; public class User { private Long id; private String name; private Integer age; private String email; //補全get、set方法 } |
3.2. 插件配置
Mybatis默認情況下,是不支持物理分頁的。默認提供的RowBounds這個分頁是邏輯分頁來的。
所謂的邏輯分頁,就是將數據庫里面的數據全部查詢出來后,在根據設置的參數返回對應的記錄。(分頁是在程序的內存中完成)。【表數據過多時,會溢出】
所謂的物理分頁,就是根據條件限制,返回指定的記錄。(分頁在數據庫里面已經完成)
MybatisPlus是默認使用RowBounds對象是支持物理分頁的。但是需要通過配置Mybatis插件來開啟。
配置代碼
<!-- 第二步:獲得會話工廠 --> <bean name="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean"> <!-- 指定數據源 --> <property name="dataSource" ref="dataSource"></property> <!-- 全局實體類配置 --> <property name="globalConfig" > <bean class="com.baomidou.mybatisplus.entity.GlobalConfiguration"> <!-- AUTO->`0`("數據庫ID自增") INPUT->`1`(用戶輸入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID") --> <property name="idType" value="0"></property> <!-- 實體類名與表名的關聯規則是,忽略前綴 --> <property name="tablePrefix" value="tb_"></property> </bean> </property> <!-- 配置插件 --> <property name="plugins"> <list> <!-- 分頁的支持 --> <bean class="com.baomidou.mybatisplus.plugins.PaginationInterceptor"> <!-- 方言 --> <!-- 我們使用的是MySQL數據庫,所以需要配置MySQL的方言 --> <property name="dialectClazz" value="com.baomidou.mybatisplus.plugins.pagination.dialects.MySqlDialect"></property> </bean> <!-- 配置支持SQL輸出 --> <bean class="com.baomidou.mybatisplus.plugins.PerformanceInterceptor"> <property name="format" value="true"></property> </bean> </list> </property> </bean> |
3.3. 自定義SQL語句支持
--實現代碼
package org.chu.mybatisplus.mapper; import java.util.List; import org.apache.ibatis.annotations.Select; import org.chu.mybatisplus.pojo.User; import com.baomidou.mybatisplus.mapper.BaseMapper; public interface UserMapper extends BaseMapper<User> { @Select(value="select * from tb_user") List<User> findAll(); } |
--測試代碼
package org.chu.test.mapper; import java.util.List;
import org.chu.mybatisplus.mapper.UserMapper; import org.chu.mybatisplus.pojo.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; //注意事項:Maven的單元測試包必須放置測試源碼包里面 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:spring-data.xml") public class UserMapperTest { @Autowired private UserMapper userMapper; @Test public void findAll() {
try { List<User> users = userMapper.findAll(); for (User user : users) { System.out.println(user.getName()); } } catch (Exception e) { e.printStackTrace(); } } } |