一、简介
1.1 概述
MyBatis-Plus(简称MP)是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。
MyBatisPlus官网:https://baomidou.com/
1.2 特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本CURD,性能基本无损耗,直接面向对象操作
- 强大的CRUD操作:内置通用Mapper、通用Service,仅仅通过少量配置即可实现单表大部分CRUD操作,更有强大的条件构造器,满足各类使用需求
- 支持Lambda形式调用:通过Lambda表达式,方便的编写各类查询条件,无需再担心字段写错
- 支持主键自动生成:支持多达4种主键策略(内含分布式唯一ID生成器-Sequence),可自由配置,完美解决主键问题
- 支持ActiveRecord模式:支持ActiveRecord形式调用,实体类只需继承Model类即可进行强大的CRUD操作
- 支持自定义全局通用操作:支持全局通用方法注入(Write once, use anywhere)
- 内置代码生成器:采用代码或者Maven插件可快速生成Mapper、Model、Service、Controller层代码,支持模板引擎,更有超多自定义配置等您来使用
- 内置分页插件:基于MyBatis物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通List查询
- 分页插件支持多种数据库:支持MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer等多种数据库
- 内置性能分析插件:可输出SQL语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
- 内置全局拦截插件:提供全表delete、update操作智能分析阻断,也可自定义拦截规则,预防误操作
1.3 支持的数据库
任何能使用MyBatis进行CRUD,并且支持标准SQL的数据库,具体支持情况如下,如果不在下列表查看分页部分教程PR您的支持。
- MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb
- 达梦数据库,虚谷数据库,人大金仓数据库,南大通用(华库)数据库,南大通用数据库,神通数据库,瀚高数据库
1.4 核心架构
二、入门案例
创建测试表- DROP TABLE IF EXISTS user;
- CREATE TABLE `user`
- (
- `id` bigint(20) NOT NULL COMMENT '主键ID',
- `name` varchar(30) DEFAULT NULL COMMENT '姓名',
- `sex` char(1) DEFAULT NULL COMMENT '性别 0:男 1:女',
- `age` int(11) DEFAULT NULL COMMENT '年龄',
- `birthday` date DEFAULT NULL COMMENT '生日',
- PRIMARY KEY (`id`)
- );
- INSERT INTO `user` VALUES (1, 'Jone', '1', 27, '2001-10-04');
- INSERT INTO `user` VALUES (2, 'Jack', '0', 20, '1999-10-04');
- INSERT INTO `user` VALUES (3, 'Tom', '1', 28, '1996-08-12');
- INSERT INTO `user` VALUES (4, 'Sandy', '1', 21, '2001-10-04');
- INSERT INTO `user` VALUES (5, 'Billie', '0', 24, '1992-09-07');
- INSERT INTO `user` VALUES (6, 'Jackson', '0', 18, '1996-08-12');
- INSERT INTO `user` VALUES (7, 'Hardy', '1', 25, '1992-09-07');
- INSERT INTO `user` VALUES (8, 'Rose', '1', 21, '1992-09-07');
- INSERT INTO `user` VALUES (9, 'June', '0', 28, '1992-09-07');
- INSERT INTO `user` VALUES (10, 'Aidan', '0', 17, '2001-10-04');
复制代码 引入依赖- <?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>com.test</groupId>
- 01_MyBatisPlus</artifactId>
- <version>1.0-SNAPSHOT</version>
- <parent>
- <groupId>org.springframework.boot</groupId>
- spring-boot-starter-parent</artifactId>
- <version>2.6.3</version>
- <relativePath/>
- </parent>
- <dependencies>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- spring-boot-starter</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>com.baomidou</groupId>
- mybatis-plus-boot-starter</artifactId>
- <version>3.4.2</version>
- </dependency>
-
- <dependency>
- <groupId>junit</groupId>
- junit</artifactId>
- <version>4.13</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>mysql</groupId>
- mysql-connector-java</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.projectlombok</groupId>
- lombok</artifactId>
- </dependency>
- </dependencies>
- </project>
复制代码 实体类- package com.test.entity;
- import lombok.AllArgsConstructor;
- import lombok.Data;
- import lombok.NoArgsConstructor;
- @Data
- @AllArgsConstructor
- @NoArgsConstructor
- public class User {
- private Long id;
- private String name;
- private String sex;
- private Integer age;
- private String birthday;
- }
复制代码 Mapper接口- package com.test.mapper;
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import com.test.entity.User;
- import org.apache.ibatis.annotations.Mapper;
- @Mapper
- public interface UserMapper extends BaseMapper<User> {
- }
复制代码 application.yml- spring:
- datasource:
- driver-class-name: com.mysql.jdbc.Driver
- url: jdbc:mysql://localhost:3306/mybatisplus?serverTimezone=GMT%2b8
- username: root
- password: admin
- #配置日志
- mybatis-plus:
- configuration:
- log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
复制代码 启动类- package com.test;
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- @SpringBootApplication
- @MapperScan("com.test.mapper")
- public class MyBatisPlusApplication {
- public static void main(String[] args) {
- SpringApplication.run(MyBatisPlusApplication.class, args);
- }
- }
复制代码 测试类- package com.test;
- import com.test.entity.User;
- import com.test.mapper.UserMapper;
- import org.junit.Assert;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.test.context.junit4.SpringRunner;
- import java.util.List;
- import javax.annotation.Resource;
- @SpringBootTest(classes = MyBatisPlusApplication.class)
- @RunWith(SpringRunner.class)
- public class Demo01 {
- @Resource
- private UserMapper userMapper;
- @Test
- public void testSelect() {
- // 传递null代表查询全部
- List<User> userList = userMapper.selectList(null);
- for (User user : userList) {
- System.out.println(user);
- }
- }
- }
复制代码 三、BaseMapper接口
在MyBatisPlus中,我们编写的Mapper接口都继承与MyBatisPlus提供的BaseMapper接口,BaseMapper接口包含了MyBatisPlus帮我们提供操作数据库的一系列方法;
官网案例:https://baomidou.com/pages/49cc81/#mapper-crud-接口
使用示例:- package com.test;
- import com.test.entity.User;
- import com.test.mapper.UserMapper;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.test.context.junit4.SpringRunner;
- import java.util.Arrays;
- import java.util.HashMap;
- import java.util.List;
- import javax.annotation.Resource;
- @SpringBootTest(classes = MyBatisPlusApplication.class)
- @RunWith(SpringRunner.class)
- public class Demo01_BaseMapper {
- @Resource
- private UserMapper userMapper;
- /**
- * 新增
- * INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
- */
- @Test
- public void insert() {
- User user = new User(100L, "Ken", "0", 20);
- userMapper.insert(user);
- }
- /**
- * 修改
- * UPDATE user SET name=?, age=?, email=? WHERE id=?
- */
- @Test
- public void update() {
- User user = new User(100L, "Kevin", "0", 25);
- userMapper.updateById(user);
- }
- /**
- * 根据id查询
- * SELECT id,name,age,email FROM user WHERE id=?
- */
- @Test
- public void selectById() {
- User user = userMapper.selectById(100L);
- System.out.println(user);
- }
- /**
- * 根据一批id查询
- * SELECT id,name,age,email FROM user WHERE id IN ( ?, ?, ? )
- */
- @Test
- public void selectBatchIds() {
- List<User> userList = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
- for (User user : userList) {
- System.out.println(user);
- }
- }
- /**
- * 根据条件查询数据
- * SELECT id,name,age,email FROM user WHERE name = ? AND id = ?
- */
- @Test
- public void selectByMap() {
- // 封装条件
- HashMap<String, Object> param = new HashMap<>();
- param.put("id", 10L);
- param.put("name", "Kevin");
- // 根据条件查询,map中的多个条件是并列关系 id=10 and name='小灰灰'
- List<User> userList = userMapper.selectByMap(param);
- for (User user : userList) {
- System.out.println(user);
- }
- }
- /**
- * 根据id删除
- * DELETE FROM user WHERE id=?
- */
- @Test
- public void deleteById() {
- userMapper.deleteById(100L);
- }
- /**
- * 根据id删除一批
- * DELETE FROM user WHERE id IN ( ?, ?, ? )
- */
- @Test
- public void deleteBatchIds() {
- userMapper.deleteBatchIds(Arrays.asList(1, 2, 3));
- }
- /**
- * 根据条件删除数据
- * DELETE FROM user WHERE name = ? AND id = ?
- */
- @Test
- public void deleteByMap() {
- // 封装条件
- HashMap<String, Object> param = new HashMap<>();
- param.put("id", 100L);
- param.put("name", "Kevin");
- userMapper.deleteByMap(param);
- }
- }
复制代码 四、Wrapper接口
通过BaseMapper提供的一些方法我们可以完成一些基本的CRUD,但无法完成复杂条件的查询;对于复杂条件的查询,MyBatisPlus提供了Wrapper接口来处理;
Wrapper是MyBatisPlus提供的一个条件构造器,主要用于构建一系列条件,当Wrapper构建完成后,可以使用Wrapper中的条件进行查询、修改、删除等操作;
Wrapper的继承体系如下:
Wrapper是条件构造抽象类,最顶端父类,其主要实现类有如下:
- AbstractWrapper:用于查询条件封装,生成sql的where条件
- QueryWrapper:Query条件封装
- UpdateWrapper:Update条件封装
- AbstractLambdaWrapper:使用Lambda语法
- LambdaQueryWrapper:基于Lambda语法使用的查询Wrapper
- LambdaUpdateWrapper:基于Lambda语法使用的更新Wrapper
官方文档:https://baomidou.com/pages/10c804/
4.1 基本方法
AbstractWrapper是其他常用Wrapper的父类,用于生成sql的where条件
4.1.1 方法介绍
AbstractWrapper提供了很多公有的方法,其子类全部具备这些方法,方法列表如下:
方法名解释示例eq等于 =eq(“name”, “老王”)--->
name = ‘老王’ne不等于 ne(“name”, “老王”)--->
name ‘老王’gt大于 >gt(“age”, 18)--->
age > 18ge大于等于 >=ge(“age”, 18)--->
age >= 18lt小于 </tdtdlt(“age”, 18)strong---></strong>
age < 18le小于等于 </strong>
age </strong>
age between 18 and 30notBetweennot between 值1 and 值2notBetween(“age”, 18, 30)--->
age not between 18 and 30likeLIKE ‘%值%’like(“name”, “王”)--->
name like ‘%王%’notLikeNOT LIKE ‘%值%’notLike(“name”, “王”)--->
name not like ‘%王%’likeLeftLIKE ‘%值’likeLeft(“name”, “王”)--->
name like ‘%王’likeRightLIKE ‘值%’likeRight(“name”, “王”)--->
name like ‘王%’isNull字段 IS NULLisNull(“name”)--->
name is nullisNotNull字段 IS NOT NULLisNotNull(“name”)--->
name is not nullin字段 IN (v0, v1, …)in(“age”, 1, 2, 3)--->
age in (1,2,3)notIn字段 NOT IN (v0, v1, …)notIn(“age”, 1, 2, 3)--->
age not in (1,2,3)inSql字段 IN ( sql语句 )inSql(“id”, “select id from table where id < 3”)--->
id in (select id from table where id < 3)notInSql字段 NOT IN ( sql语句 )notInSql(“id”, “select id from table where id < 3”)--->
id not in (select id from table where id < 3)groupBy分组:GROUP BY 字段, …groupBy(“id”, “name”)--->
group by id,nameorderByAsc排序:ORDER BY 字段, … ASCorderByAsc(“id”, “name”)--->
order by id ASC,name ASCorderByDesc排序:ORDER BY 字段, … DESCorderByDesc(“id”, “name”)--->
order by id DESC,name DESCorderBy排序:ORDER BY 字段, …orderBy(true, true, “id”, “name”)--->
order by id ASC,name ASChavingHAVING ( sql语句 )例1:having(“sum(age) > 10”)--->
having sum(age) > 10
例2:having(“sum(age) > {0}”, 11)--->
having sum(age) > 11func主要解决条件拼接func(i -> if(true) {i.eq(“id”, 1)} else {i.ne(“id”, 1)})or拼接 OReq(“id”,1).or().eq(“name”,“老王”)--->
id = 1 or name = ‘老王’andAND 嵌套and(i -> i.eq(“name”, “李白”).ne(“status”, “活着”))--->
and (name = ‘李白’ and status ‘活着’)nested用于多条件拼接时nested(i -> i.eq(“name”, “李白”).ne(“status”, “活着”))--->
(name = ‘李白’ and status ‘活着’)apply用于拼接SQL语句例1:apply(“id = 1”)--->
id = 1
例2:apply(“id = {0}”,1)--->
id = 1
例3:apply(“name like {0} and age > {1}”,“%J%”,18) --->
name like ‘%J%’ and age > 18last无视优化规则直接拼接到 sql 的最后last(“limit 1”) --->
在SQL语句最后面拼接:limit 1exists拼接 EXISTS ( sql语句 )exists(“select id from table where age = 1”)--->
exists (select id from table where age = 1)notExists拼接 NOT EXISTS ( sql语句 )notExists(“select id from table where age = 1”)--->
not exists (select id from table where age = 1)创建Wrapper对象:
- Wrappers静态方法:
- public static QueryWrapper query()
- 通过QueryWrapper对象的构造方法:
代码示例:- @SpringBootTest(classes = MyBatisPlusApplication.class)
- @RunWith(SpringRunner.class)
- public class Demo02_Wrapper {
- @Resource
- private UserMapper userMapper;
- /**
- * QueryWrapper的创建
- * SELECT id,name,age,email FROM user
- */
- @Test
- public void test1() {
- // 创建QueryWrapper,默认情况下查询所有数据
- QueryWrapper<User> wrapper = Wrappers.query();
- QueryWrapper<User> wrapper2 = new QueryWrapper<>();
- List<User> users = userMapper.selectList(wrapper);
- users.forEach(System.out::println);
- }
- }
复制代码 4.1.2 基本方法的使用
官网案例:https://baomidou.com/pages/10c804/#abstractwrapper
使用示例:- @Test
- public void test2() {
- QueryWrapper<User> wrapper = Wrappers.query();
- // name ='Jack'
- // wrapper.eq("name","Jack");
- //参数1: 是否要进行name条件的拼接
- String name = "Jack";
- wrapper.eq(StringUtils.isNotBlank(name), "name", name);
- // name != 'Jack'
- // wrapper.ne("name","Jack");
- // age > 20
- // wrapper.gt("age",20);
- // age < 20
- // wrapper.lt("age",20);
- // age=20
- // wrapper.lt("age",20);
- // age between 20 and 24
- // wrapper.between("age",20,24);
- // age not between 20 and 24
- // wrapper.notBetween("age",20,24);
- // name like "%J%" 自动拼接左右的%
- // wrapper.like("name","J");
- // name not like "%J%"
- // wrapper.notLike("name","J");
- // name like "%J"
- // wrapper.likeLeft("name","J");
- // name like 'J%'
- // wrapper.likeRight("name","J");
- // name is null
- // wrapper.isNull("name");
- // name is not null
- // wrapper.isNotNull("name");
- // name in ('Jack','Tom','Jone')
- // wrapper.in("name","Jack","Tom","Jone");
- // name not in ('Jack','Tom','Jone')
- // wrapper.notIn("name","Jack","Tom","Jone");
- List<User> users = userMapper.selectList(wrapper);
- users.forEach(System.out::println);
- }
复制代码 4.1.3 子查询
示例代码:- @Test
- public void test3() {
- // 创建wrapper对象
- QueryWrapper<User> wrapper = Wrappers.query();
- // 相当于: name in (select name from user where age > 21)
- wrapper.inSql("name", "select name from user where age > 21");
- // 相当于: name not in (select name from user where age > 21)
- // wrapper.notInSql("name","select name from user where age > 21");
- List<User> users = userMapper.selectList(wrapper);
- users.forEach(System.out::println);
- }
复制代码 4.1.4 分组与排序
1)分组:
通过Wrapper.query()构建的查询字段默认是表中的所有字段,因此在这种情况下分组是没有意义的,分组具体的用法我们后面再详细介绍;- @Test
- public void test4() {
- // 创建wrapper对象
- QueryWrapper<User> wrapper = Wrappers.query();
- // 相当于 select * from user where group sex
- // 这是一个没有意义的分组,分组必须结合查询的字段来体现,后续学QueryWrapper的select方法再介绍
- wrapper.groupBy("sex");
- List<User> users = userMapper.selectList(wrapper);
- users.forEach(System.out::println);
- }
复制代码 2)having操作- @Test
- public void test5() {
- // 创建wrapper对象
- QueryWrapper<User> wrapper = Wrappers.query();
- // group by sex having sex = 0
- wrapper.groupBy("sex");
- wrapper.having("sex", "0");
- List<User> users = userMapper.selectList(wrapper);
- users.forEach(System.out::println);
- }
复制代码 3)排序:- @Test
- public void test6() {
- // 创建wrapper对象
- QueryWrapper<User> wrapper = Wrappers.query();
- /**
- * 参数1: 是否是Asc排序(升序), true : asc排序, false: desc排序
- * 参数2: 排序的字段
- */
- // wrapper.orderByAsc("age"); // order by age asc
- // wrapper.orderByDesc("age"); // order by age desc
- List<User> users = userMapper.selectList(wrapper);
- users.forEach(System.out::println);
- }
复制代码 4.1.5 多条件的拼接
Wrapper对象在调用每一个方法时都会返回当前对象(Wrapper),这样可以很好的方便我们链式编程;另外MyBatisPlus在拼接多个条件时默认使用and拼接,如果需要使用or,那么需要显示的调用or()方法;
1)and拼接条件:- @Test
- public void test7() {
- //创建wrapper对象
- QueryWrapper<User> wrapper = Wrappers.query();
- // 默认情况下,多条件是以and拼接
- // SQL语句: name LIKE "%a%" AND age > 20 AND sex = 0
- wrapper.like("name", "%a%")
- .lt("age", 20)
- .eq("sex", 0);
- List<User> users = userMapper.selectList(wrapper);
- users.forEach(System.out::println);
- }
复制代码 2)or拼接条件:- @Test
- public void test8() {
- // 创建wrapper对象
- QueryWrapper<User> wrapper = Wrappers.query();
- /*
- 默认情况下,多条件是以and拼接
- SQL语句: name LIKE "%a%" OR age > 20 AND sex = 0
- */
- wrapper.like("name", "%a%")
- .or()
- .lt("age", 20)
- .eq("sex", 0); // 该条件仍然以AND拼接
- List<User> users = userMapper.selectList(wrapper);
- users.forEach(System.out::println);
- }
复制代码 4.1.6 其他方法
1)and方法:用于拼接一个其他的整体条件;示例如下:- @Test
- public void test1() {
- QueryWrapper<User> wrapper = Wrappers.query();
- // 生成的SQL为: (age < ? AND (sex = ? OR name LIKE ?))
-
- // wrapper.lt("age", 20);
- // wrapper.and(new Consumer<QueryWrapper<User>>() {
- // @Override
- // public void accept(QueryWrapper<User> userQueryWrapper) {
- // userQueryWrapper.eq("sex", 0)
- // .or()
- // .like("name", "J");
- // }
- // });
-
- // 生成的SQL为: (age < ? AND sex = ? OR name LIKE ?)
- wrapper.lt("age", 20)
- .eq("sex", 0)
- .or()
- .like("name", "J");
- List<User> users = userMapper.selectList(wrapper);
- users.forEach(System.out::println);
- }
复制代码 2)func方法:用于多条件的拼接,直接使用之前的方法也可以做到这个功能;示例如下:- @Test
- public void test2() {
- QueryWrapper<User> wrapper = Wrappers.query();
- // 生成的SQL语句条件: (age < ? AND name LIKE ? AND sex = ?)
- wrapper.lt("age", 20);
- wrapper.func(new Consumer<QueryWrapper<User>>() {
- @Override
- public void accept(QueryWrapper<User> userQueryWrapper) {
- userQueryWrapper.like("name", "a");
- userQueryWrapper.eq("sex", "0");
- }
- });
- // 等价于:
- // wrapper.lt("age", 20)
- // .like("name", "a")
- // .eq("sex", "0");
- List<User> users = userMapper.selectList(wrapper);
- users.forEach(System.out::println);
- }
复制代码 3)nested方法:功能等价于and方法- @Test
- public void test3() {
- QueryWrapper<User> wrapper = Wrappers.query();
- // 生成的SQL语句条件为: (id = ? AND (name LIKE ? OR age > ?))
- // nested()等价于and方法()
- wrapper.eq("id", 1);
- wrapper.nested(new Consumer<QueryWrapper<User>>() {
- @Override
- public void accept(QueryWrapper<User> userQueryWrapper) {
- // 默认情况下是用and来拼接多个条件
- userQueryWrapper.like("name", "a")
- .or().gt("age", 20);
- }
- });
- List<User> users = userMapper.selectList(wrapper);
- users.forEach(System.out::println);
- }
复制代码 4)apply方法:可以使用占位符进行参数传参;示例如下:- @Test
- public void test4() {
- QueryWrapper<User> wrapper = Wrappers.query();
- // SQL: (name like ? and age > ?)
- // wrapper.apply("name like {0} and age > {1}", "%J%", 18);
- // SQL: (date_format(birthday, '%Y-%m-%d') = ?)
- wrapper.apply("date_format(birthday, '%Y-%m-%d') = {0}", "2001-10-04");
- List<User> users = userMapper.selectList(wrapper);
- users.forEach(System.out::println);
- }
复制代码 5)last方法:无视优化规则直接拼接到 sql 的最后,只能调用一次,多次调用以最后一次为准 有sql注入的风险
Tips:apply方法可以防止SQL注入,但last方法不能;
- @Test
- public void test5() {
- QueryWrapper<User> wrapper = Wrappers.query();
- // 无视优化规则直接拼接到 sql 的最后,只能调用一次,多次调用以最后一次为准 有sql注入的风险
- // SQL: name = 'Jone'
- // String name = "Jone";
- // wrapper.last("where name = '" + name + "'");
- // SQL: SELECT id,name,sex,age FROM user where name ='' or 1=1; -- '
- String name = "' or 1=1; -- ";
- wrapper.last("where name ='" + name + "'"); // 出现SQL注入问题
- List<User> users = userMapper.selectList(wrapper);
- users.forEach(System.out::println);
- }
复制代码 6)exists方法:用于exists语句- @Test
- public void test6() {
- QueryWrapper<User> wrapper = Wrappers.query();
- // SQL: (EXISTS (select 1))
- wrapper.exists("select 1");
- List<User> users = userMapper.selectList(wrapper);
- users.forEach(System.out::println);
- }
复制代码 7)notExists方法:- @Test
- public void test7() {
- QueryWrapper<User> wrapper = Wrappers.query();
- // SQL: (NOT EXISTS (select 1))
- wrapper.notExists("select 1");
- List<User> users = userMapper.selectList(wrapper);
- users.forEach(System.out::println);
- }
复制代码 4.2 QueryWrapper
QueryWrapper是AbstractWrapper的子类,主要用于查询指定字段,方法列表如下:
方法名解释示例select(String… sqlSelect)设置查询字段例1:select(“id”, “name”, “age”)
例2:select(i -> i.getProperty().startsWith(“test”))示例代码:- package com.test;
- import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.test.entity.User;
- import com.test.mapper.UserMapper;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.test.context.junit4.SpringRunner;
- import javax.annotation.Resource;
- import java.util.List;
- @SpringBootTest(classes = MyBatisPlusApplication.class)
- @RunWith(SpringRunner.class)
- public class Demo04_QueryWrapper {
- @Resource
- private UserMapper userMapper;
- // 选择查询的字段
- @Test
- public void test1() throws Exception {
- QueryWrapper<User> wrapper = Wrappers.query();
- // 确定要查询的字段
- wrapper.select("id", "name", "sex");
- // in
- wrapper.in("id", "1", "2");
- // SQL: SELECT id,name,sex FROM user WHERE (id IN (?,?))
- List<User> userList = userMapper.selectList(wrapper);
- userList.forEach(System.out::println);
- }
- @Test
- public void test2() throws Exception {
- User user = new User();
- user.setId(1L);
- // user当做查询的条件
- QueryWrapper<User> wrapper = Wrappers.query(user);
- // 指定查询的列
- wrapper.select("id", "name", "sex");
- // SQL: SELECT id,name,sex FROM user WHERE id=?
- List<User> userList = userMapper.selectList(wrapper);
- userList.forEach(System.out::println);
- }
- }
复制代码 4.3 UpdateWrapper
UpdateWrapper也是AbstractWrapper的子类,因此UpdateWrapper也具备之前的那些查询方法,不同的是,UpdateMapper在那些方法基础之上还提供了很多有关于更新操作的方法;
方法如下:
方法名解释示例set(String column, Object val)设置查询字段例1:set("name", "老李头")
例2:set("name", "")
—>数据库字段值变为空字符串
例3:set("name", null)
—>数据库字段值变为nullsetSql(String sql)设置set子句的部分SQL例1:setSql("name = '老李头'")
例2:setSql("name = '老李头',age=20 where id=1")示例代码:- package com.test;
- import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.test.entity.User;
- import com.test.mapper.UserMapper;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.test.context.junit4.SpringRunner;
- import javax.annotation.Resource;
- import java.util.List;
- @SpringBootTest(classes = MyBatisPlusApplication.class)
- @RunWith(SpringRunner.class)
- public class Demo05_UpdateWrapper {
- @Resource
- private UserMapper userMapper;
- @Test
- public void test1() throws Exception {
- UpdateWrapper<User> wrapper = Wrappers.update();
- // UpdateWrapper也是AbstractWrapper的子类,因此也具备一些基本的查询方法
- wrapper.like("name", "J");
- List<User> userList = userMapper.selectList(wrapper);
- for (User user : userList) {
- System.out.println(user);
- }
- }
- /**
- * 第一种方法: 使用wrapper来修改,并且指定查询条件
- *
- * @throws Exception
- */
- @Test
- public void test2() throws Exception {
- UpdateWrapper<User> wrapper = Wrappers.update();
- wrapper.set("name", "Jackson");
- wrapper.set("age", "16");
- wrapper.set("sex", "1");
- wrapper.eq("id", 2L);
- // SQL: UPDATE user SET name=?, sex=?, age=? WHERE (id = ?)
- userMapper.update(null, wrapper);
- }
- /**
- * 第二种方法: 使用wrapper来封装条件,使用entity来封装修改的数据
- *
- * @throws Exception
- */
- @Test
- public void test3() throws Exception {
- UpdateWrapper<User> wrapper = Wrappers.update();
- wrapper.eq("id", 2L);
- User user = new User(null, "Jack", "0", 28);
- // SQL: UPDATE user SET name=?, sex=?, age=? WHERE (id = ?)
- userMapper.update(user, wrapper);
- }
- /**
- * 第三种方法: Wrappers.update(user)传递查询的条件,使用wrapper来修改
- *
- * @throws Exception
- */
- @Test
- public void test4() throws Exception {
- User user = new User();
- user.setId(1L);
- // user当做查询条件
- UpdateWrapper<User> wrapper = Wrappers.update(user);
- wrapper.set("name", "xiaohui");
- wrapper.set("sex", "0");
- wrapper.set("age", "22");
- // SQL : UPDATE user SET name=?,sex=?,age=? WHERE id=?
- userMapper.update(null, wrapper);
- }
- /**
- * setSql方法
- *
- * @throws Exception
- */
- @Test
- public void test5() throws Exception {
- UpdateWrapper<User> wrapper = Wrappers.update();
- wrapper.setSql("name='abc',sex='0',age=18 where id=1");
- // SQL: UPDATE user SET name='abc',sex='0',age=18 where id=1
- userMapper.update(null, wrapper);
- }
- }
复制代码 4.4 LambdaQueryWrapper
LambdaQueryWrapper是QueryWrapper的子类,具备QueryWrapper的所有方法,QueryWrapper的方法上提供了一系列有关于方法引的操作;
使用示例:- package com.test;
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.test.entity.User;
- import com.test.mapper.UserMapper;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.test.context.junit4.SpringRunner;
- import java.util.List;
- import javax.annotation.Resource;
- @SpringBootTest(classes = MyBatisPlusApplication.class)
- @RunWith(SpringRunner.class)
- public class Demo06_LambdaQueryWrapper {
- @Resource
- private UserMapper userMapper;
- /**
- * 使用QueryWrapper
- * @throws Exception
- */
- @Test
- public void test1() throws Exception {
- QueryWrapper<User> wrapper = Wrappers.query();
- wrapper.eq("id", "1");
- List<User> userList = userMapper.selectList(wrapper);
- for (User user : userList) {
- System.out.println(user);
- }
- }
- /**
- * 使用LambdaQueryWrapper
- * @throws Exception
- */
- @Test
- public void test2() throws Exception {
- LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
- // id=1
- // wrapper.eq(User::getId,1);
- // select id,name,age from user where id in (1,2,3) and name like "%a%"
- wrapper.in(User::getId, "1", "2", "3")
- .like(User::getName, "a")
- .select(User::getId, User::getName, User::getAge);
- List<User> userList = userMapper.selectList(wrapper);
- for (User user : userList) {
- System.out.println(user);
- }
- }
- }
复制代码 4.5 LambdaUpdateMapper
LambdaUpdateMapper同样是UpdateMapper的子类,具备UpdateMapper的所有方法,UpdateMapper的方法上提供了一系列有关于方法引的操作;
示例代码:- package com.test;
- import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
- import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.test.entity.User;
- import com.test.mapper.UserMapper;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.test.context.junit4.SpringRunner;
- import javax.annotation.Resource;
- @SpringBootTest(classes = MyBatisPlusApplication.class)
- @RunWith(SpringRunner.class)
- public class Demo07_LambdaUpdateWrapper {
- @Resource
- private UserMapper userMapper;
- /**
- * 使用UpdateWrapper
- *
- * @throws Exception
- */
- @Test
- public void test1() throws Exception {
- UpdateWrapper<User> wrapper = Wrappers.update();
- wrapper.eq("id", "1");
- wrapper.set("name", "xiaohui");
- wrapper.set("age", 20);
- userMapper.update(null, wrapper);
- }
- /**
- * 使用LambdaUpdateWrapper
- *
- * @throws Exception
- */
- @Test
- public void test2() throws Exception {
- LambdaUpdateWrapper<User> wrapper = Wrappers.lambdaUpdate();
- wrapper.eq(User::getId, "1");
- wrapper.set(User::getName, "xiaolan");
- wrapper.set(User::getAge, 18);
- userMapper.update(null, wrapper);
- }
- }
复制代码 五、Mapper分页查询
5.1 配置
在MyBatis中提供有Page对象来帮助我们实现分页查询,在Page对象中有如下成员:
成员变量说明List getRecords()当前页数据public long getTotal()总记录数public long getSize()页大小public long getCurrent()当前页default long getPages()总页数public boolean hasNext()是否有上一页public boolean hasPrevious()是否有上一页MyBatisPlus的分页逻辑底层是通过分页插件来完成的,因此我们首先要配置MyBatisPlus的分页插件;
配置分页插件:- package com.test.config;
- import com.baomidou.mybatisplus.annotation.DbType;
- import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
- import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- @Configuration
- @MapperScan("com.test.mapper") // mapper接口的所在位置
- public class MyBatisPlusConfig {
- @Bean
- public MybatisPlusInterceptor mybatisPlusInterceptor() {
- MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
- interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
- return interceptor;
- }
- }
复制代码 5.2 分页查询
在BaseMapper中主要提供有如下方法来完成分页查询:
- E selectPage(E page, @Param(Constants.WRAPPER) Wrapper queryWrapper):
- 参数1:分页配置类
- 参数2:分页查询条件
- 解释:根据分页配置和分页查询条件来完成分页查询,当前页数据为指定类型
- E selectMapsPage(E page, @Param(Constants.WRAPPER) Wrapper queryWrapper)
- 参数1:分页配置类
- 参数2:分页查询条件
- 解释:根据分页配置和分页查询条件来完成分页查询,当前页数据为Map类型
1)无条件分页查询:- package com.test;
- import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
- import com.test.entity.User;
- import com.test.mapper.UserMapper;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.test.context.junit4.SpringRunner;
- import java.util.List;
- import javax.annotation.Resource;
- @SpringBootTest(classes = MyBatisPlusApplication.class)
- @RunWith(SpringRunner.class)
- public class Demo06_BaseMapper {
- @Resource
- private UserMapper userMapper;
- /**
- * 无条件分页查询
- * @throws Exception
- */
- @Test
- public void test1() throws Exception {
- // 封装分页信息
- Page<User> page = new Page<>(1, 3);
- /*
- 执行分页查询,并将结果封装到page中
- 参数1: 分页配置
- 参数2: 查询条件
- */
- userMapper.selectPage(page, null);
- // 当前页数据
- List<User> pageData = page.getRecords();
- for (User user : pageData) {
- System.out.println(user);
- }
- System.out.println("------------");
- System.out.println("当前页:" + page.getCurrent());
- System.out.println("每页显示的条数:" + page.getSize());
- System.out.println("总记录数:" + page.getTotal());
- System.out.println("总页数:" + page.getPages());
- System.out.println("是否有上一页:" + page.hasPrevious());
- System.out.println("是否有下一页:" + page.hasNext());
- }
- }
复制代码 查询结果:- # 首先查询总记录数
- ==> Preparing: SELECT COUNT(*) FROM user
- ==> Parameters:
- <== Columns: COUNT(*)
- <== Row: 10
- <== Total: 1
- # 再查询分页
- ==> Preparing: SELECT id,name,sex,age FROM user LIMIT ?
- ==> Parameters: 3(Long)
- <== Columns: id, name, sex, age
- <== Row: 1, Jone, 1, 27
- <== Row: 2, Jack, 0, 20
- <== Row: 3, Tom, 1, 28
- <== Total: 3
- Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@226eba67]
- User(id=1, name=Jone, sex=1, age=27)
- User(id=2, name=Jack, sex=0, age=20)
- User(id=3, name=Tom, sex=1, age=28)
- ------------
- 当前页:1
- 每页显示的条数:3
- 总记录数:10
- 总页数:4
- 是否有上一页:false
- 是否有下一页:true
- 2022-11-15 15:28:16 INFO 8724 --- com.zaxxer.hikari.HikariDataSource: HikariPool-1 - Shutdown initiated...
- 2022-11-15 15:28:16 INFO 8724 --- com.zaxxer.hikari.HikariDataSource: HikariPool-1 - Shutdown completed.
- Process finished with exit code 0
复制代码 九、ActiveRecord使用
9.1 ActiveRecord简介
ActiveRecord也属于ORM(对象关系映射)层,由Rails最早提出,遵循标准的ORM模型:表映射到记录,记录映射到对象,字段映射到对象属性。配合遵循的命名和配置惯例,能够很大程度的快速实现模型的操作,而且简洁易懂。
ActiveRecord的主要思想是:
1)每一个数据库表对应创建一个类,类的每一个对象实例对应于数据库中表的一行记录,通常表的每个字段在类中都有相应的Field;
2)ActiveRecord同时负责把自己持久化,在ActiveRecord中封装了对数据库的访问,即CURD;
3)ActiveRecord是一种领域模型(Domain Model),封装了部分业务逻辑。
简而言之,AR建立了Java对象与数据库表逻辑上的直接映射,方便了程序的编写。而在MyBatisPlus中使用AR非常简单,只需让JavaBean继承Model类即可。
9.2 Model类使用
在MyBatisPlus中,只要将我们的JavaBean继承与Model类即可获取AR功能,即JavaBean自身实现自身的CURD;
让JavaBean继承Model:- /**
- * 带条件分页查询
- *
- * @throws Exception
- */
- @Test
- public void test2() throws Exception {
- QueryWrapper<User> wrapper = Wrappers.query();
- wrapper.like("name", "a");
- // 封装分页信息
- Page<User> page = new Page<>(1, 3);
- /*
- 执行分页查询,并将结果封装到page中
- 参数1: 分页配置
- 参数2: 查询条件
- */
- userMapper.selectPage(page, wrapper);
- // 当前页数据
- List<User> pageData = page.getRecords();
- for (User user : pageData) {
- System.out.println(user);
- }
- System.out.println("------------");
- System.out.println("当前页:" + page.getCurrent());
- System.out.println("每页显示的条数:" + page.getSize());
- System.out.println("总记录数:" + page.getTotal());
- System.out.println("总页数:" + page.getPages());
- System.out.println("是否有上一页:" + page.hasPrevious());
- System.out.println("是否有下一页:" + page.hasNext());
- }
复制代码 测试代码:- ==> Preparing: SELECT COUNT(*) FROM user WHERE (name LIKE ?)
- ==> Parameters: %a%(String)
- <== Columns: COUNT(*)
- <== Row: 5
- <== Total: 1
- ==> Preparing: SELECT id,name,sex,age FROM user WHERE (name LIKE ?) LIMIT ?
- ==> Parameters: %a%(String), 3(Long)
- <== Columns: id, name, sex, age
- <== Row: 2, Jack, 0, 20
- <== Row: 4, Sandy, 1, 21
- <== Row: 6, Jackson, 0, 18
- <== Total: 3
- Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@58a2b4c]
- User(id=2, name=Jack, sex=0, age=20)
- User(id=4, name=Sandy, sex=1, age=21)
- User(id=6, name=Jackson, sex=0, age=18)
- ------------
- 当前页:1
- 每页显示的条数:3
- 总记录数:5
- 总页数:2
- 是否有上一页:false
- 是否有下一页:true
复制代码 十、多数据源配置
1)引入多数据源依赖:- /**
- * 查询结果以Map返回
- *
- * @throws Exception
- */
- @Test
- public void test3() throws Exception {
- // 封装分页信息
- Page page = new Page<>(1, 3);
- userMapper.selectMapsPage(page, null);
- // 每一条记录都是一个HashMap
- List<HashMap<String, Object>> pageData = page.getRecords();
- for (HashMap userMap : pageData) {
- System.out.println(userMap);
- }
- System.out.println("------------");
- System.out.println("当前页:" + page.getCurrent());
- System.out.println("每页显示的条数:" + page.getSize());
- System.out.println("总记录数:" + page.getTotal());
- System.out.println("总页数:" + page.getPages());
- System.out.println("是否有上一页:" + page.hasPrevious());
- System.out.println("是否有下一页:" + page.hasNext());
- }
复制代码 2)准备两个数据库- ==> Preparing: SELECT COUNT(*) FROM user
- ==> Parameters:
- <== Columns: COUNT(*)
- <== Row: 10
- <== Total: 1
- ==> Preparing: SELECT id,name,sex,age FROM user LIMIT ?
- ==> Parameters: 3(Long)
- <== Columns: id, name, sex, age
- <== Row: 1, Jone, 1, 27
- <== Row: 2, Jack, 0, 20
- <== Row: 3, Tom, 1, 28
- <== Total: 3
- Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7123be6c]
- {sex=1, name=Jone, id=1, age=27}
- {sex=0, name=Jack, id=2, age=20}
- {sex=1, name=Tom, id=3, age=28}
- ------------
- 当前页:1
- 每页显示的条数:3
- 总记录数:10
- 总页数:4
- 是否有上一页:false
- 是否有下一页:true
- 2022-11-15 15:50:37 INFO 20980 --- com.zaxxer.hikari.HikariDataSource: HikariPool-1 - Shutdown initiated...
- 2022-11-15 15:50:37 INFO 20980 --- com.zaxxer.hikari.HikariDataSource: HikariPool-1 - Shutdown completed.
- Process finished with exit code 0
复制代码 3)多数据源配置:- package com.test.service;
- import com.baomidou.mybatisplus.extension.service.IService;
- import com.test.entity.User;
- public interface IUserService extends IService<User> {
- }
复制代码 4)启动类:- package com.test;
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- @SpringBootApplication
- @MapperScan("com.test.mapper")
- public class MyBatisPlusApplication {
- public static void main(String[] args) {
- SpringApplication.run(MyBatisPlusApplication.class, args);
- }
- }
复制代码 5)实体类:- package com.test;
- import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
- import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
- import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
- import com.test.entity.User;
- import com.test.service.IUserService;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.test.context.junit4.SpringRunner;
- import java.util.HashMap;
- import java.util.List;
- import javax.annotation.Resource;
- @SpringBootTest(classes = MyBatisPlusApplication.class)
- @RunWith(SpringRunner.class)
- public class Demo07_Service {
- @Resource
- private IUserService userService;
- /**
- * 新增
- *
- * @throws Exception
- */
- @Test
- public void test1() throws Exception {
- User user = new User(null, "xiaohui", "0", 20);
- userService.save(user);
- }
- /**
- * 如果id存在则修改,不存在则新增
- *
- * @throws Exception
- */
- @Test
- public void test2() throws Exception {
- User user = new User(1L, "xiaohui", "0", 20);
- userService.saveOrUpdate(user);
- }
- /**
- * 根据id删除
- *
- * @throws Exception
- */
- @Test
- public void test3() throws Exception {
- userService.removeById(1L);
- }
- /**
- * 根据id修改
- *
- * @throws Exception
- */
- @Test
- public void test4() throws Exception {
- User user = new User(1L, "xiaolan", "1", 18);
- userService.updateById(user);
- }
- /**
- * 根据id查询
- *
- * @throws Exception
- */
- @Test
- public void test5() throws Exception {
- User user = userService.getById(1L);
- System.out.println(user);
- }
- /**
- * 查询列表
- *
- * @throws Exception
- */
- @Test
- public void test6() throws Exception {
- QueryWrapper<User> wrapper = Wrappers.query();
- wrapper.in("id", "1", "2");
- // 查询所有
- // List<User> userList = userService.list();
- // 通过wrapper查询
- List<User> userList = userService.list(wrapper);
- for (User user : userList) {
- System.out.println(user);
- }
- }
- /**
- * 查询总记录数
- *
- * @throws Exception
- */
- @Test
- public void test7() throws Exception {
- QueryWrapper<User> wrapper = Wrappers.query();
- wrapper.like("name", "a");
- // 查询总记录数
- //int count = userService.count();
- // 根据条件查询总记录数
- int count = userService.count(wrapper);
- System.out.println(count);
- }
- /**
- * 分页查询(当前页类型为指定类型)
- *
- * @throws Exception
- */
- @Test
- public void test8() throws Exception {
- Page<User> page = new Page<>(1, 3);
- userService.page(page);
- // 当前页数据
- List<User> pageData = page.getRecords();
- for (User user : pageData) {
- System.out.println(user);
- }
- System.out.println("------------");
- System.out.println("当前页:" + page.getCurrent());
- System.out.println("每页显示的条数:" + page.getSize());
- System.out.println("总记录数:" + page.getTotal());
- System.out.println("总页数:" + page.getPages());
- System.out.println("是否有上一页:" + page.hasPrevious());
- System.out.println("是否有下一页:" + page.hasNext());
- }
-
- /**
- * 分页查询(当前页结果为HashMap类型)
- *
- * @throws Exception
- */
- @Test
- public void test9() throws Exception {
- Page page = new Page<>(1, 3);
- userService.pageMaps(page);
- // 当前页数据
- List<HashMap<String, Object>> pageData = page.getRecords();
- for (HashMap userMap : pageData) {
- System.out.println(userMap);
- }
- System.out.println("------------");
- System.out.println("当前页:" + page.getCurrent());
- System.out.println("每页显示的条数:" + page.getSize());
- System.out.println("总记录数:" + page.getTotal());
- System.out.println("总页数:" + page.getPages());
- System.out.println("是否有上一页:" + page.hasPrevious());
- System.out.println("是否有下一页:" + page.hasNext());
- }
-
- /**
- * 链式查询
- *
- * @throws Exception
- */
- @Test
- public void test10() throws Exception {
- QueryChainWrapper<User> chainWrapper = userService.query();
- // SQL: SELECT id,name,age FROM user WHERE (id IN (?,?,?) AND name LIKE ?)
- List<User> userList = chainWrapper.select("id", "name", "age")
- .in("id", "1", "2", "3")
- .like("name", "a")
- .list();
- for (User user : userList) {
- System.out.println(user);
- }
- }
-
- /**
- * 链式修改
- *
- * @throws Exception
- */
- @Test
- public void test11() throws Exception {
- UpdateChainWrapper<User> chainWrapper = userService.update();
- // SQL: UPDATE user SET age=? WHERE (id IN (?,?) OR sex = ?)
- chainWrapper.in("id","1","2")
- .or()
- .eq("sex","0")
- .set("age",20)
- .update();
- }
- }
复制代码 6)编写两个Mapper:- @Data
- @AllArgsConstructor
- @NoArgsConstructor
- @TableName("t_user")
- public class User {
- private Long id;
- private String name;
- private String sex;
- private Integer age;
- }
复制代码- mybatis-plus:
- global-config: # MyBatisPlus全局配置
- db-config: # 配置数据库
- table-prefix: t_ #配置表名前缀为t_
复制代码 7)测试类:- @Data
- @AllArgsConstructor
- @NoArgsConstructor
- @TableName("t_user")
- public class User {
- // 将当前属性所对应的字段作为主键
- @TableId
- private Long id;
- private String name;
- private String sex;
- private Integer age;
- }
复制代码 来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |