MyBatis-Plus簡介和快速入門教程
一、MyBatis-Plus簡介(來自官網(wǎng))
MyBatis-Plus,簡稱MP,是一個MyBatis的增強工具,在MyBatis的基礎(chǔ)上只做增強不做修改,為簡化開發(fā)、提高效率而生。
特性:
- 無侵入:只做增強不做改變,引入它不會對現(xiàn)有工程產(chǎn)生影響,如絲般順滑
- 損耗小:啟動即會自動注入基本 CURD,性能基本無損耗,直接面向?qū)ο蟛僮?/li>
- 強大的 CRUD 操作:內(nèi)置通用 Mapper、通用 Service,僅僅通過少量配置即可實現(xiàn)單表- 大部分 CRUD 操作,更有強大的條件構(gòu)造器,滿足各類使用需求
- 支持 Lambda 形式調(diào)用:通過 Lambda 表達式,方便的編寫各類查詢條件,無需再擔(dān)心字段寫錯
- 支持主鍵自動生成:支持多達 4 種主鍵策略(內(nèi)含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解決主鍵問題
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式調(diào)用,實體類只需繼承 Model 類即可進行強大的 CRUD 操作
- 支持自定義全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 內(nèi)置代碼生成器:采用代碼或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 層代碼,支持模板引擎,更有超多自定義配置等您來使用
- 內(nèi)置分頁插件:基于 MyBatis 物理分頁,開發(fā)者無需關(guān)心具體操作,配置好插件之后,寫分頁等同于普通 List 查詢
- 分頁插件支持多種數(shù)據(jù)庫:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多種數(shù)據(jù)庫
- 內(nèi)置性能分析插件:可輸出 SQL 語句以及其執(zhí)行時間,建議開發(fā)測試時啟用該功能,能快速揪出慢查詢
- 內(nèi)置全局攔截插件:提供全表 delete 、 update 操作智能分析阻斷,也可自定義攔截規(guī)則,預(yù)防誤操作
二、快速開始
步驟一、新建數(shù)據(jù)庫表,寫對應(yīng)的JavaBean類。
首先我們還是使用我們之前Mybatis建的student表吧。(這里,四個屬性的名稱前面的s_被我又去掉了)

然后為我們的表格創(chuàng)建一個Bean。
package com.example.po;
public class Student {
private Integer id;
private String name;
private String email;
private Integer age;
public Student() {
}
public Student(Integer id, String name, String email, Integer age) {
this.id = id;
this.name = name;
this.email = email;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", age=" + age +
'}';
}
}
步驟二、添加依賴
mybatis和mybatis-plus會自動維護我們的mybatis 以及mybatis-spring相關(guān)的依賴
<dependencies>
<!--mybatisPlus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.4.3</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<!--log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--c3p0-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--數(shù)據(jù)庫驅(qū)動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!--spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.3.9</version>
</dependency>
</dependencies>
步驟三、寫配置文件
mybatis的配置文件:
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>
</configuration>
log4j.xml日志
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<!-- 日志輸出到控制臺 -->
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<!--編碼格式-->
<param name="Encoding" value="UTF-8"/>
<!-- 日志輸出格式 -->
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%p][%d{yyyy-MM-dd HH:mm:ss SSS}][%c]-[%m]%n"/>
</layout>
</appender>
<logger name="java.sql">
<level value ="debug"/>
</logger>
<logger name="org.apache.ibatis">
<level value="info"/>
</logger>
<root>
<level value="debug"/>
<appender-ref ref="STDOUT"/>
</root>
</log4j:configuration>
db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost/mybatis?useSSL=false&serverTimezone=UTC 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"
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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--數(shù)據(jù)源-->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--事務(wù)管理器-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--基于注解的事務(wù)管理-->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
<!--配置MyBatisPlus的MybatisSqlSessionFactoryBean-->
<bean id="sqlSessionFactoryBean" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<!--數(shù)據(jù)源-->
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--別名處理-->
<property name="typeAliasesPackage" value="com.example.po"/>
</bean>
<!--配置mybatis掃描mapper接口的路徑-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.dao"/>
</bean>
</beans>
步驟四、集成MP(Mybatis-Plus,后邊都直接簡稱MP)
MP的集成非常簡單,對于Spring,我們僅僅需要把Mybatis自帶的MyBatisSqlSessionFactory替換為MP自帶的即可。也就是剛才applicationContext.xml文件中的這一段:
如果是Mybatis的話,那么class的值是org.mybatis.spring.SqlSessionFactoryBean

三、通用CRUD
準備完畢,現(xiàn)在我們可以開始進行我們的CRUD了。(開始爽了)
首先,說一下之前我們使用mybatis的做法吧:
步驟:
1、創(chuàng)建dao接口
2、寫接口方法
3、創(chuàng)建mapper文件,并為每個接口方法寫sql語句
4、在mybatis的主配置文件注冊mapper
然后我們再說一下MP的做法:
步驟:
1、創(chuàng)建dao接口,繼承BaseMapper<T>接口,<T>傳入他對應(yīng)的實體類。
就沒了??。?!沒錯,就這一部,不需要寫我們的xml文件。MP已經(jīng)幫我們?nèi)紝懞昧?。我們直接寫測試代碼:
3.1 insert(插入操作)
package com.example.text;
import com.example.dao.StudentDao;
import com.example.po.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
private ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
private StudentDao studentDao = context.getBean("studentDao",StudentDao.class);
//通用插入操作
@Test
public void testInsert(){
//初始化Student
Student student = new Student(null,"林八","linba@163.com",23);
int num = studentDao.insert(student);
System.out.println("成功添加"+num+"條記錄");
}
}
執(zhí)行后,看我們的數(shù)據(jù)庫(添加成功)

插入后,我們甚至可以直接獲取自增的id值如下:
@Test
public void testInsert(){
//初始化Student
Student student = new Student(null,"張飛","liubei@163.com",30);
int num = studentDao.insert(student);
System.out.println("成功添加"+num+"條記錄");
//插入操作執(zhí)行后,我們可以獲取自增的主鍵值
int id = student.getId();
System.out.println("插入的主鍵值為:"+id);
}
數(shù)據(jù)庫:

控制臺:

3.2 updateById(更新操作)
直接傳入一個Student對象即可。(除id值外,其他值都可為空,為空的字段不會出現(xiàn)在sql語句中)
直接寫測試方法:
//通用更新操作
@Test
public void testUpdateById(){
//初始化Student
Student student = new Student(1004,"關(guān)羽","guanyu@qq.com",29);
int result = studentDao.updateById(student);
System.out.println("成功修改"+result+"條記錄");
}
數(shù)據(jù)庫:

3.3 查詢操作——各種select
通過id查詢:selectById
@Test
public void testSelectById(){
Student student = studentDao.selectById(1007);
System.out.println(student);
}
顯示:

使用and查詢單條記錄:selectOne(返回復(fù)數(shù)記錄的話會報錯)
@Test
public void testSelectOne(){
//寫個匿名類,設(shè)置我們要查詢的組合條件的實體類
Wrapper<Student> stu = new Wrapper<Student>() {
@Override
public Student getEntity() {
return new Student(null,"關(guān)羽",null,29);
}
@Override
public MergeSegments getExpression() {
return null;
}
@Override
public void clear() {
}
@Override
public String getSqlSegment() {
return null;
}
};
Student student = studentDao.selectOne(stu);
System.out.println(student);
}
結(jié)果:

使用in通過id值查詢多條記錄(selectBatchIds)
@Test
public void testSelectBatchIds(){
List<Integer> ids = new ArrayList<>();
ids.add(1001);
ids.add(1002);
List<Student> students = studentDao.selectBatchIds(ids);
for (Student stu:students){
System.out.println(stu);
}
}
顯示:

傳入Map通過and查詢?nèi)舾蓷l數(shù)據(jù):selectByMap
@Test
public void testSelectByMap(){
Map<String,Object> map = new HashMap<>();
//map的鍵必須跟表中的列名相同
map.put("s_name","張飛");
map.put("s_age",28);
List<Student> students = studentDao.selectByMap(map);
for (Student stu:students){
System.out.println(stu);
}
}
結(jié)果:

3.4 刪除操作——各種delete
- 通過id刪除記錄:deleteById
- 通過多個id刪除多條記錄:deleteBatchIds
- 通過and組合條件刪除記錄:deleteByMap
@Test
public void testDeleteById(){
int result = studentDao.deleteById(1001);
System.out.println("成功刪除"+result+"條記錄");
}
@Test
public void testDeleteBatchIds(){
List<Integer> ids = new ArrayList<>();
ids.add(1002);
ids.add(1003);
int result = studentDao.deleteBatchIds(ids);
System.out.println("成功刪除"+result+"條記錄");
}
@Test
public void testDeleteByMap(){
Map<String,Object> map = new HashMap<>();
map.put("s_id",1005);
map.put("s_name","劉七");
int result = studentDao.deleteByMap(map);
System.out.println("成功刪除"+result+"條記錄");
}
依次執(zhí)行上面的方法,控制臺和數(shù)據(jù)庫顯示:






附加1:如果表名或者表中屬性的名稱與我們實體類的名稱不同解決方法
假如現(xiàn)在,我們的表名叫mp_student
屬性名分別叫s_id,s_name,s_email,s_age。
那么,我們就要在實體類
1、用@TableName對實體類進行標注
2、用@IdName對主鍵進行標注
3、用@TableField對非主鍵進行標注
如下:
package com.example.po;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
@TableName(value = "mp_student")
public class Student {
/*
* TableId標注這個是主鍵
* value值告訴MP這個主鍵在表中的屬性名(相同其實也可以省略不寫)
* type值有以下幾個,分別表示:
* AUTO 數(shù)據(jù)庫ID自增
* NONE 無狀態(tài),該類型為未設(shè)置主鍵類型(注解里等于跟隨全局,全局里約等于 INPUT)
* INPUT insert前自行set主鍵值
* ASSIGN_ID 分配ID(主鍵類型為Number(Long和Integer)或String)(since 3.3.0),使用接口IdentifierGenerator的方法nextId(默認實現(xiàn)類為DefaultIdentifierGenerator雪花算法)
* ASSIGN_UUID 分配UUID,主鍵類型為String(since 3.3.0),使用接口IdentifierGenerator的方法nextUUID(默認default方法)
* */
@TableId(value = "s_id", type = IdType.AUTO)
private Integer id;
@TableField(value = "s_name")
private String name;
@TableField(value = "s_email")
private String email;
@TableField(value = "s_age")
private Integer age;
public Student() {
}
public Student(Integer id, String name, String email, Integer age) {
this.id = id;
this.name = name;
this.email = email;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", age=" + age +
'}';
}
}
注意:設(shè)置主鍵的type=AUTO的話,必須要數(shù)據(jù)庫中對主鍵設(shè)置自增,并設(shè)置自增的起始值才行。設(shè)置如下:
選擇自己的數(shù)據(jù)庫表,然后點擊Design Table

選中主鍵,然后點擊下面的Auto Increment(自增)

點擊Option菜單項,設(shè)置自增的起始值。

順便說下,TableName和TableField這兩個注釋,他們也有自己的其他屬性值:
到此這篇關(guān)于MyBatis-Plus簡介和快速入門教程的文章就介紹到這了,更多相關(guān)MyBatis-Plus入門內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Spring接口集成Caffeine+Redis兩級緩存
這篇文章主要介紹了基于Spring接口集成Caffeine+Redis兩級緩存,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-07-07
Spring?Boot攔截器和監(jiān)聽器實現(xiàn)對請求和響應(yīng)處理實戰(zhàn)
這篇文章主要介紹了Spring?Boot攔截器和監(jiān)聽器實現(xiàn)對請求和響應(yīng)處理實戰(zhàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06
SpringBoot整合阿里云OSS對象存儲服務(wù)實現(xiàn)文件上傳
這篇文章主要介紹了SpringBoot整合阿里云OSS對象存儲實現(xiàn)文件上傳,幫助大家更好的理解和學(xué)習(xí)使用SpringBoot,感興趣的朋友可以了解下2021-04-04

