環境:spring boot +maven+MySQL
一、Mybatis-plus簡介:
Mybatis vs JPA
Mybatis優勢:
1)SQL語句可以自由控制,更靈活,性能更高
2)SQL與代碼分離,易於閱讀和維護
3)提供XML標籤,支持編寫動態SQL語句
劣勢:
1)簡單的CRUD操作還得寫SQL語句
2)XML中有大量的SQL要維護
3)MyBatis自身功能很有限,但支持Plugin
JPA優勢:
1)JPA移植性比較好(JPQL)
2)提供了很多CRUD方法、開發效率高
3)對象化程度更高
Mybatis-Plus就是解決Mybatis中的一些缺點。
Mybatis-Plus(簡稱MP)是一個 Mybatis 的增強工具,在 Mybatis 的基礎上只做增強不做改變,爲簡化開發、提高效率而生。這是官方給的定義,關於mybatis-plus的更多介紹及特性,可以參考mybatis-plus官網。那麼它是怎麼增強的呢?其實就是它已經封裝好了一些crud方法,我們不需要再寫xml了,直接調用這些方法就行,就類似於JPA。
二、MyBatis-Plus特性
1、無侵入、損耗小、強大的CRUD功能
2、支持Lambda形式調用、支持多種數據庫
3、支持主鍵自動生成、支持ActiveRecord模式
4、支持自定義全局通用操作、支持關鍵詞自動轉義
5、內置強大的代碼生成器、內置分頁插件、內置性能分析插件
6、內置全局攔截插件、內置sql注入剝離器
三、安裝及配置
引入依賴
Maven:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
application.yml:
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.0.1:3306/hfs?useUnicode=true&characterEncoding=utf-8
username: #
password: #
logging:
level:
root: warn
org.hthc.db.dao: trace
配置 MapperScan 註解
@SpringBootApplication
@MapperScan("com.baomidou.mybatisplus.samples.quickstart.mapper")//mapper包名
public class Application {
public static void main(String[] args) {
SpringApplication.run(QuickStartApplication.class, args);
}
}
entity 略
mapper 略
四、常用註解
@TableName
描述:表名註解
@TableId
描述:主鍵註解
@TableFieId
描述:字段註解(非主鍵)
排除非表字段的三種方式:
//1、加上關鍵字 transient 不參與序列號過程
private transient String test;
//2、標識爲靜態變量,可參與序列號過程
private static String test;
//3、使用@TableField(exist=false) 註解
@TableField(exist=false)
private String test;
五、MP的CRUD
查詢所有用戶
@Autowired
private UserMapper userMapper; //注入userMapper
@Test //測試方法
void selectAll() {
List<sysUser> list = userMapper.selectList(null); //查詢所有用戶
list.forEach(System.out::println);
}
1、insert操作
實體插入
@Autowired
private UserMapper userMapper;
@Test
public void insert(){
User user = new User();
user.setName("張三")
user.setAge(18);
int rows = userMapper.insert(user);
System.out.println("影響記錄數:"+rows);
}
2、select操作
普通查詢
1)根據ID查詢
User user = userMapper.selectById(24);
2) 根據ID批量查詢
List<Int> idsList = Arrays.asList(11,23,52,36);
List<User> userList = userMapper.selectBatchIds(idsList);
userList.forEach(System.out::println);
3) 使用Map根據條件查詢返回多條數據
Map<String, Object> columnMap = new HashMap<String, Object>();
columnMap.put("name","張三");
columnMap.put("age",25);
//相當於 where name="張三" and age=25 map的鍵相當於數據表中的列
List<User> userList = userMapper.selectByMap(columnMap);
條件構造器查詢
構造器創建:
1、QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
2、QueryWrapper<User> query = Wrappers.<User>query();
1、名字中包含雨並且年齡小於40
name like '%雨%' and age<40
QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
queryWrapper.like("name","雨").lt("age",40);
List<User> userList = userMapper.selectList(queryWrapper );
2、名字中包含雨並且年齡大於等於20且小於等於40並且Email不爲空
//name like '%雨%' and age between 20 and 40 and email is not null
queryWrapper.like("name","雨").between("age",20, 40).isNotNull("email")
3、名字爲王姓或者年齡大於等於25,按照年齡降序排序,年齡相同按照ID升序排序
//name like '王%' or age >= 40 order by age desc, id asc
queryWrapper.likeRight("name","王").or().ge("age", 25).orderByDesc("age").orderByAsc("id");
4、創建日期爲2019年2月14日並且直屬上級爲名字爲王姓
apply(String applySql, Object... params)
apply("date_format(create_time,'%Y-%m-%d') = '2019-02-14' ") 有注入風險
apply("date_format(create_time,'%Y-%m-%d') = {0}","2019-02-14") 無注入風險
//date_format(create_time,'%Y-%m-%d') and manager_id in (select id from user where name like '王%')
queryWrapper.apply("date_format(create_time,'%Y-%m-%d') = {0}","2019-02-14").inSql("manager_id", "select id from user where name like '王%'");
5、名字爲王姓並且(年齡小於40或郵箱不爲空)
//name like '王%' and (age<40 or email is not null)
queryWrapper.likeRight("name", "王").and(wq->wq.lt("age").or().isNotNull("email"));
6、名字爲王姓或者(年齡小於40並且年齡大於20並且郵箱不爲空)
//name like '王%' or (age<40 and age >20 and email is not null)
queryWrapper.likeRight("name", "王").or(wq->wq.lt("age",40).gt("age",20).isNotNull("email"));
7、(年齡小於40或郵箱不爲空) 並且名字爲王姓
//(age<40 or email is not null) and name like '%王'
queryWrapper.nested(wq->wq.lt("age", 40).or().isNotNull("email")).likeRight("name","王");
8、年齡爲30、31、34、35
//age in (30、31、34、35)
queryWrapper.in("age",Arrays.asList(30,31,34,35))
9、只返回滿足條件的其中一條語句即可
//limit 1
queryWrapper.in("age",Arrays.asList(30,31,34,35)).last("limit 1");
//last 無視優化規則直接拼接到sql最後
select中字段不全出現的處理方法
10、名字中包含雨並且年齡小於40(需求1加強版)
第一種情況: select id, name from user where name like '%雨%' and age<40
第二種情況:select id, name, age, email from user where name like '%雨%' and age<40
//第一種情況
queryWrapper.select("id","name").like("name","雨").lt("age",40);
queryWrapper.like("name","雨").lt("age",40).select("id","name");
//第二種情況
queryWrapper.like("name","雨").lt("age",40).select(User.class, info->!info.getColumn().equals("create_time")&&!info.getColumn().equals("manager_id"));
條件構造器中condition作用
condition是執行條件,表示該條件是否加入最後生成的SQL語句中,爲true則添加
//條件查詢 判斷名字或者郵箱是否爲空,不爲空則添加sql去查詢
queryWrapper.like(StringUtils.isNotEmpty(name), "name", name)
.like(StringUtils.isNotEmpty(email, "email", email));
創造條件構造器時傳入實體對象
默認實體對象不爲空的屬性將作爲查詢條件,默認使用等值條件符
User whereUser = new User();
whereUser.setName("劉強");
whereUser.setAge(32);
QueryWrapper<User> queryWrapper = new QueryWrapper<User>(whereUser);
條件構造器中allEq用法
allEq(Map<R, V> params)
params: key 爲數據庫字段, value 爲字段值
//where id = 1 and name = '老王' and age is null
allEq({id:1, name:"老王", age: null})
allEq(Map<R,V> params, boolean null2IsNull)
null2IsNull: 爲true則在map中的value爲null時調用isNull方法,爲false時則忽略value爲null的
//where id = 1 and name = '老王'
allEq({id:1, name:"老王", age: null}, false)
其他條件構造器
11、按照直屬上級分組,查詢每組的平均年齡、最大年齡、最小年齡。並且只取年齡總和小於500的組
//select avg(age) avg_age, min(age) min_age, max(age) max_age
// from user group by manager_id having sum(age) < 500
queryWrapper.select("avg(age) avg_age","min(age) min_age", "max(age) max_age")
.groupBy("manager_id").having("sum(age)<{0}", 500);
userMapper.selectMaps(queryWrappr);
Lambda條件構造器
三種方式創建lambda構造器
1、new QueryWrapper<User>().lambda();
2、new LambdaQueryWrapper<User>();
3、Wrappers.<User>lambdaQuery();
//where name like '%雨%' and age < 40
lambdaQuery.like(User::getName, "雨").lt(User::getAge,40);
好處在於防誤寫
new LambdaQueryChainWrapper<User>(userMapper).like(User::getName, "雨")
.ge(User::getAge, 20).list();
使用條件構造器的自定義SQL
更新方法
1、通過ID
2、通過條件構造器
//set age = 30 where name = '李' and age = 29
updateWrapper.eq("name","李").eq("age", 29).set("age", 30);
刪除方法