Mybatis-Plus入門學習筆記(一)
本文內容
- 瞭解Mybatis-Plus
- 整合Mybatis-Plus
1、瞭解Mybatis-plus
1.1、Mybatis-Plus介紹
MyBatis-Plus(簡稱 MP)是一個 MyBatis 的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高
效率而生。
願景
我們的願景是成為 MyBatis 最好的搭檔,就像 魂鬥羅 中的 1P、2P,基友搭配,效率翻倍。
1.2、程式碼以及文件
文件地址:https://mybatis.plus/guide/
原始碼地址:https://github.com/baomidou/mybatis-plus
1.3、特性
- 無侵入:只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑
- 損耗小:啟動即會自動注入基本 CURD,效能基本無損耗,直接面向物件操作
- 強大的 CRUD 操作:內建通用 Mapper、通用 Service,僅僅通過少量配置即可實現單表大部分 CRUD 操作,
更有強大的條件構造器,滿足各類使用需求 - 支援 Lambda 形式呼叫:通過 Lambda 表示式,方便的編寫各類查詢條件,無需再擔心欄位寫錯
- 支援多種資料庫:支援 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、
SQLServer2005、SQLServer 等多種資料庫 - 支援主鍵自動生成:支援多達 4 種主鍵策略(內含分散式唯一 ID 生成器 - Sequence),可自由配置,完美解
決主鍵問題 - 支援 XML 熱載入:Mapper 對應的 XML 支援熱載入,對於簡單的 CRUD 操作,甚至可以無 XML 啟動
- 支援 ActiveRecord 模式:支援 ActiveRecord 形式呼叫,實體類只需繼承 Model 類即可進行強大的 CRUD 操
作 - 支援自定義全域性通用操作:支援全域性通用方法注入( Write once, use anywhere )
- 支援關鍵詞自動轉義:支援資料庫關鍵詞(order、key......)自動轉義,還可自定義關鍵詞
- 內建程式碼生成器:採用程式碼或者 Maven 外掛可快速生成 Mapper 、 Model 、 Service 、 Controller 層程式碼,
- 支援模板引擎,更有超多自定義配置等您來使用
- 內建分頁外掛:基於 MyBatis 物理分頁,開發者無需關心具體操作,配置好外掛之後,寫分頁等同於普通 List
查詢 - 內建效能分析外掛:可輸出 Sql 語句以及其執行時間,建議開發測試時啟用該功能,能快速揪出慢查詢
- 內建全域性攔截外掛:提供全表 delete 、 update 操作智慧分析阻斷,也可自定義攔截規則,預防誤操作
- 內建 Sql 注入剝離器:支援 Sql 注入剝離,有效預防 Sql 注入攻擊
1.4、架構
1.5、作者
Mybatis-Plus是由baomidou(苞米豆)組織開發並且開源的,目前該組織大概有30人左右。
碼雲地址:https://gitee.com/organizations/baomidou
2、快速開始
對於Mybatis整合MP有常常有三種用法,分別是
- Mybatis+MP
- Spring+Mybatis+MP
- Spring Boot+Mybatis+MP。
2.1、建立資料庫以及表
2.2、建立工程
-
匯入依賴
<?xml version="1.0" encoding="UTF-8"?> <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>cn.itcast.mp</groupId> <artifactId>itcast-mybatis-plus</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <modules> <module>itcast-mybatis-plus-simple</module> <module>itcast-mybatis-plus-spring</module> </modules> <dependencies> <!-- mybatis-plus外掛依賴 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>3.1.1</version> </dependency> <!-- MySql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!-- 連線池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.11</version> </dependency> <!--簡化bean程式碼的工具包--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> <version>1.18.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.4</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
2.3、Mybatis + MP
2.3.1、建立子Module
-
匯入父工程
<?xml version="1.0" encoding="UTF-8"?> <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"> <parent> <artifactId>itcast-mybatis-plus</artifactId> <groupId>cn.itcast.mp</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>itcast-mybatis-plus-simple</artifactId> </project>
-
log4j.properties
log4j.rootLogger=DEBUG,A1 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n
2.3.2、Mybatis實現查詢User表
-
編寫mybatis-config.xml檔案:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="UserMapper.xml"/> </mappers> </configuration>
-
編寫User實體物件:(這裡使用lombok進行了進化bean操作)
@Data @NoArgsConstructor @AllArgsConstructor public class User { private Long id; private String userName; private String password; private String name; private Integer age; private String email; }
-
編寫UserMapper介面:
public interface UserMapper { List<User> findAll(); }
-
編寫UserMapper.xml檔案:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.itcast.mp.simple.mapper.UserMapper"> <select id="findAll" resultType="cn.itcast.mp.simple.pojo.User"> select * from tb_user </select> </mapper>
-
編寫TestMybatis測試用例:
public class TestMybatis { @Test public void testFindAll() throws Exception{ String config = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(config); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); //測試查詢 List<User> users = userMapper.findAll(); for (User user : users) { System.out.println(user); } } }
-
測試結果
2.3.3、Mybatis+MP實現查詢User
-
將UserMapper繼承BaseMapper,將擁有了BaseMapper中的所有方法:
public interface UserMapper extends BaseMapper<User> { List<User> findAll(); }
-
使用MP中的MybatisSqlSessionFactoryBuilder程序構建:
0public class TestMybatisPlus { @Test public void testFindAll() throws Exception{ String config = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(config); SqlSessionFactory sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); //測試查詢 //List<User> users = userMapper.findAll(); //可以呼叫BaseMapper中定義的方法 List<User> users = userMapper.selectList(null); for (User user : users) { System.out.println(user); } } }
執行報錯:
解決:在User物件中新增@TableName,指定資料庫表名
測試:
簡單說明:
-
由於使用了MybatisSqlSessionFactoryBuilder進行了構建,繼承的BaseMapper中的方法就載入到了
SqlSession中,所以就可以直接使用相關的方法 -
如圖
-
2.4、Spring + Mybatis + MP
- 引入了Spring框架,資料來源、構建等工作就交給了Spring管理。
2.4.1、建立子Module
<?xml version="1.0" encoding="UTF-8"?>
<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">
<parent>
<artifactId>itcast-mybatis-plus</artifactId>
<groupId>cn.itcast.mp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>itcast-mybatis-plus-spring</artifactId>
<properties>
<spring.version>5.1.6.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</project>
2.4.2、實現查詢User
-
編寫jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false jdbc.username=root jdbc.password=root
-
編寫applicationContext.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" 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.xsd"> <context:property-placeholder location="classpath:*.properties"/> <!-- 定義資料來源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="driverClassName" value="${jdbc.driver}"/> <property name="maxActive" value="10"/> <property name="minIdle" value="5"/> </bean> <!--這裡使用MP提供的sqlSessionFactory,完成了Spring與MP的整合--> <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> <property name="globalConfig"> <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig"> <property name="dbConfig"> <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig"> <property name="idType" value="AUTO"/> </bean> </property> </bean> </property> </bean> <!--掃描mapper介面,使用的依然是Mybatis原生的掃描器--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.itcast.mp.simple.mapper"/> </bean> </beans>
-
編寫User物件以及UserMapper介面:
@Data @NoArgsConstructor @AllArgsConstructor @TableName("tb_user") public class User { private Long id; private String userName; private String password; private String name; private Integer age; private String email; }
public interface UserMapper extends BaseMapper<User> { }
-
編寫測試用例:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml") public class TestMybatisSpring { @Autowired private UserMapper userMapper; @Test public void testSelectList(){ List<User> users = this.userMapper.selectList(null); for (User user : users) { System.out.println(user); } } }
測試
2.5、SpringBoot + Mybatis + MP
- 使用SpringBoot將進一步的簡化MP的整合,需要注意的是,由於使用SpringBoot需要繼承parent,所以需要重新建立工程,並不是建立子Module。
2.5.1、建立工程
2.5.2、匯入依賴
<?xml version="1.0" encoding="UTF-8"?>
<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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<groupId>cn.itcast.mp</groupId>
<artifactId>itcast-mp-springboot</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--簡化程式碼的工具包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--mybatis-plus的springboot支援-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<!--mysql驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
log4j.properties:
log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n
2.5.3、編寫application.properties
spring.application.name = itcast-mp-springboot
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mp?
useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL
=false
spring.datasource.username=root
spring.datasource.password=root
2.5.4、編寫pojo
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_user")
public class User {
// @TableId(type = IdType.AUTO)
private Long id;
private String userName;
@TableField(select = false) //查詢時不返回該欄位的值
private String password;
private String name;
private Integer age;
@TableField(value = "email") //指定資料表中欄位名
private String mail;
@TableField(exist = false)
private String address; //在資料庫表中是不存在的
}
2.5.5、編寫mapper
package cn.itcast.mp.mapper;
import cn.itcast.mp.pojo.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface UserMapper extends BaseMapper<User> {
}
2.5.6、編寫啟動類
package cn.itcast.mp;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
@MapperScan("cn.itcast.mp.mapper") //設定mapper介面的掃描包
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
2.5.7、編寫測試用例
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class TestMybatisSpringBoot {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectList(){
List<User> users = this.userMapper.selectList(null);
for (User user : users) {
System.out.println(user);
}
}
}