前言
項目開發(fā)一直使用MyBatis , 簡單,方便斯辰,容易上手,調優(yōu)比其他的ORM框架容易的多坡疼。最近一次偶然的搜索彬呻,發(fā)現了MyBatis Plus, 試用之后,真是太爽了柄瑰。MyBatis Plus是攻城獅的福利废岂,幾乎不用編碼就可以完成單表的CRUD操作。使用心得做個記錄狱意。
一湖苞、準備環(huán)境
IDE編輯器:IntelliJ IDEA 2018.2.4(Ultimate Edition)
數據庫:MySQL 5.7
框架:MyBatis Plus 3.05 , Spring Boot 2.0.6
管理工具:Maven 3.3.9
JDK:jdk1.8或以上
1. IDEA設置
idea是java開發(fā)的利器详囤,我個人的常用設置有這么幾項:
1) 設置自動導入包
2) 設置提示快捷鍵
idea默認的代碼提示是ctrl + 空格财骨,常和輸入法沖突,可以改為 alt + /,特別是從Eclipse轉過來的同學藏姐,alt + / 比較順手隆箩。
3) 設置多Tab標簽
idea默認代碼區(qū)的Tab標簽是單行顯示,多文件時不方便羔杨。
4) 設置提示不區(qū)分大小寫
idea默認是按首字母大小寫匹配捌臊,進行代碼提示, 例如輸入FileReader,必須F是大寫才有提示兜材, 設置完成后 f 也可以有提示理澎。
5) 設置的包顯示風格
2. 安裝其他軟件
安裝jdk1.8 , mysql 5.7 ,maven3以上版本
二逞力、初識 MyBatis Plus
官網:MyBatis Plus
MyBatis Plus 簡稱MP, 是MyBatis的增強糠爬,不做改變寇荧,只做增強。簡單而又強大执隧。
MP是一只帶著藍色面罩的小鳥揩抡。
1. 功能特性
- 無侵入:只做增強不做改變,引入它不會對現有工程產生影響镀琉,如絲般順滑
- 損耗小:啟動即會自動注入基本 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 物理分頁堤魁,開發(fā)者無需關心具體操作喂链,配置好插件之后,寫分頁等同于普通 List 查詢
- 內置性能分析插件:可輸出 Sql 語句以及其執(zhí)行時間姨涡,建議開發(fā)測試時啟用該功能衩藤,能快速揪出慢查詢
- 內置全局攔截插件:提供全表 delete 、 update 操作智能分析阻斷涛漂,也可自定義攔截規(guī)則赏表,預防誤操作
- 內置 Sql 注入剝離器:支持 Sql 注入剝離,有效預防 Sql 注入攻擊
以上特性大多都是項目開發(fā)中必用的功能匈仗。
2. 開始上手
MP主頁有示例瓢剿,按照例子步驟就可以快速搭建MP項目。
-
準備表 student
主鍵是id字段悠轩, auto increment
student.png
-
創(chuàng)建Spring Boot項目
建議使用 Spring Initializr间狂,依賴項選擇MySQL
創(chuàng)建springboot項目
-
pom.xml
工程屬性
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
parent依賴項
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
SpringBoot 依賴項
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
MyBatis Plus依賴項
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
MySQL 依賴項
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
-
配置數據庫信息
編輯resource/application.yml文件,使用默認的application.properties文件也是可以的火架,兩種類型的文件作用一樣鉴象,語法格式有區(qū)別。
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8
username: test
password: 123456
-
創(chuàng)建entity類
創(chuàng)建Student類何鸡,屬性名和列名相同
public class Student {
//指定主鍵為 自動增長(mysql的 auto increment)
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
private String name;
private Integer age;
private String email;
private Integer status;
private Date createtime;
// set | get
- 創(chuàng)建Mapper接口
public interface StudentMapper extends BaseMapper<Student> {
//無需任何內容
}
-
測試insert
在test/java/ 目下創(chuàng)建測試類纺弊,使用@Test修飾測試方法
@SuppressWarnings("all")
@RunWith(SpringRunner.class)
@SpringBootTest
public class MPTest {
@Autowired
private StudentMapper studentMapper;
@Test
public void testInsertStudent(){
Student student = new Student();
student.setName("李名");
student.setAge(20);
student.setEmail("liming@163.com");
student.setStatus(1);
student.setCreatetime( new Date());
int rows = studentMapper.insert(student);
System.out.println("insert 結果:"+rows);
}
}
三、實體屬性名和列名相同
上面“2 開始上手”骡男,實體類屬性名和表的列名是相同的淆游,使用MP無需設置,就可以完成CRUD, 在這部分繼續(xù)實行其他的單表操作隔盛。
1. 增加數據
同“2 開始上手”中的測試部分的代碼犹菱,首先創(chuàng)建實體對象, 給屬性賦值吮炕,調用studentMapper的insert(),參數是實體類對象腊脱, insert()返回值是數據庫插入成功的行數。整數值龙亲。
//添加記錄虑椎,并獲取新記錄的注解
@Test
public void testInsertStudent() {
Student student = new Student();
student.setName("周新");
student.setAge(20);
student.setEmail("liming@163.com");
student.setStatus(1);
student.setCreatetime(new Date());
int rows = studentMapper.insert(student);
// 主鍵是id,獲取新添加記錄的id俱笛,使用對象的getId()
int newId = student.getId();
System.out.println("insert 結果:" + rows + "|對象的id:"+newId);
}
輸出:insert 結果:1|對象的id:8
捆姜, id是你插入數據主鍵和我的不同。
2.修改數據
//根據主鍵修改對象
@Test
public void testUpdateStudent(){
Student student = new Student();
student.setId(8);
student.setName("新的名字");
student.setAge(30);
//根據主鍵修改對象迎膜, 對象null的屬性泥技,不進行修改
int rows = studentMapper.updateById(student);
}
首先給要修改的屬性賦值,null的屬性磕仅,不會參與修改珊豹。update set 列名=值不會出現null的字段簸呈;條件部分是 where id= 8;
注意:MP判斷是否修改字段是判斷屬性的null,最好實體類Student的屬性都是引用類型店茶, 包括Integer age , 這樣不給age賦值蜕便,就不會更新age字段。如果實體類定義 int age 贩幻。
//根據主鍵修改對象
@Test
public void testUpdateStudent(){
Student student = new Student();
student.setId(8);
student.setName("新的名字");
//student.setAge(30);
//根據主鍵修改對象轿腺, 對象null的屬性,不進行修改
int rows = studentMapper.updateById(student);
}
MP的執(zhí)行sql: UPDATE student SET name=?, age=? WHERE id=?
修改結果是 age 是 0 丛楚, 因為Student屬性 int age 族壳,這樣定義int類型默認初值是 0 。
updateById()是根據主鍵作為添加更新趣些,還可以根據其他條件更新仿荆,例如update(實體對象, Wrapper)坏平, Wrapper的使用后面會說到拢操。
3. 刪除數據
BaseMapper中刪除方法
deleteBatchIds(Collection); 參數是主鍵的集合,刪除多條數據
delete(Wrapper); 根據Wrapper對象的條件舶替,刪除數據
deleteById(主鍵id);根據單一主鍵令境,刪除數據
deleteByMap(Map<String,Object>); 使用Map作為條件刪除數據
//刪除數據
@Test
public void testDeleteStudent(){
// sql : DELETE FROM student WHERE id=?
int rows = studentMapper.deleteById(2);
System.out.println("deleteById結果:"+rows);
}
注:deleteById(), 參數是主鍵值, 刪除條件是 where id = 2
@Test
public void testDeleteStudent2(){
Map<String,Object> condition = new HashMap<>();
condition.put("name","周新");
condition.put("age",20);
int rows = studentMapper.deleteByMap(condition);
System.out.println("deleteByMap 結果:"+rows);
}
注:創(chuàng)建Map, 添加條件數據坎穿。Map的key是字段名,value是字段的值返劲。調用deleteByMap(); 傳入Map對象玲昧。 返回值成功刪除的行數。
@Test
public void testDeleteStudent3(){
//DELETE FROM student WHERE name = ? OR age > ?
QueryWrapper<Student> wrapper = new QueryWrapper<>();
wrapper.eq("name", "周新")
.or()
.gt("age", 20);
int rows = studentMapper.delete(wrapper);
System.out.println("delete(wrapper) 結果:"+rows);
}
注:Wrapper是抽象類篮绿,QueryWrapper是他的子類孵延, 用來封裝條件字段和字段值。 eq()表示等于=亲配, or() 是字段之間用 or 連接尘应, gt()是大于。這些只是Wrapper中的幾個方法吼虎, 參數是字段名犬钢,不是屬性名。
4. 查詢數據
BaseMapper的多個查詢方法
selectBatchIds(Collection); 查詢集合中多個主鍵值數據
selectByMap(Map<String,Object>); 根據Map條件查詢
selectList(Wrapper); 使用Wrapper對象作為查詢條件
selectById(id); 根據主鍵值查詢
selectPage(IPage, Wrapper); 根據Wrapper條件并進行分頁
selectCount(Wrapper); 統(tǒng)一記錄數量
selectOne(Wrapper); 查詢結果是一個對象
使用selectById , selectOne查詢數據思灰, 其他查詢方法后面有單獨的章節(jié)玷犹,獨立講查詢的各種使用方式。
@Test
public void testSelectStudent(){
// SELECT id,name,age,email,status,createtime FROM student WHERE id=?
Student student = studentMapper.selectById(8);
System.out.println("根據id查詢結果:"+student);
}
@Test
public void testSelectStudent2(){
QueryWrapper<Student> condition = new QueryWrapper<>();
condition.eq("name","李名");
//SELECT id,name,age,email,status,createtime FROM student WHERE name = ?
Student student = studentMapper.selectOne(condition);
System.out.println("selectOne查詢結果:"+student);
}
注:先創(chuàng)建Wrapper對象洒疚,添加查詢條件歹颓, 調用selectOne()方法坯屿。 selectOne()的查詢結果必須小于或等于一條記錄,MP內部是調用的MyBatis的selectOne()方法巍扛,多于一個記錄领跛,系統(tǒng)會報錯,錯誤提示如下:
org.apache.ibatis.exceptions.TooManyResultsException