一、起步
1、前置知识
2、项目背景
在线教育顾名思义,是以网络为介质的教学方式,通过网络,学员与教师即使相隔万里也可以开展教学活动;此外,借助网络课件,学员还可以随时随地进行学习,真正打破了时间和空间的限制,对于工作繁忙,学习时间不固定的职场人而言网络远程教育是最方便不过的学习方式。
3、项目采用的商业模式
- B2C 模式(Business To Customer 会员模式):
此项目采用B2C
- B2B2C 模式:(商家到商家到用户)
4、项目功能模块
5、项目中使用的技术栈
二、谷粒学院项目简介
1、功能简介
谷粒学院,是一个 B2C 模式的职业技能在线教育系统,分为前台用户系统和后台运营平台。
2、系统模块
在这里插入图片描述
3、系统架构
三、MybatisPlus
简介
1、简介
官网:http://mp.baomidou.com/
参考教程:http://mp.baomidou.com/guide/
MyBatis-Plus
(简称 MP)是一个 MyBatis
的增强工具,在 Mybatis
的基础上只做增强不做改变,为简化
开发、提高效率而生。
2、特性
快速开始参考:http://mp.baomidou.com/guide/quick-start.html
测试项目: mybatis_plus
数据库:mybatis_plus
四、MybatisPlus
入门
1、创建并初始化数据库
I、创建数据库:
mybatis_plus
II、创建 User 表:
其表结构如下:
其对应的 SQL
脚本如下:
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
DELETE FROM user;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
2、初始化工程
IDEA 工具使用 Spring Initializr
快速初始化一个 Spring Boot 工程。
版本:2.2.1.RELEASE
3、添加依赖
I、引入依赖:
spring-boot-starter
、spring-boot-starter-test
添加:mybatis-plus-boot-starter
、MySQL
、lombok
在项目中使用 Lombok
可以减少很多重复代码的书写。比如说 getter/setter/toString
等方法的编写。
<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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</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>
</dependency>
<!--lombok用来简化实体类-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
注意:引入 MyBatis-Plus
之后请不要再次引入 MyBatis
以及 MyBatis-Spring
,以避免因版本差异导致的问
题。
II、idea中安装 Lombok
插件:
4、配置
在 application.properties
配置文件中添加 MySQL
数据库的相关配置:
mysql 5.x.x
# mysql数据库连接
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus
spring.datasource.username=root
spring.datasource.password=1234567890
mysql 8.x.x
以上(spring boot 2.1
)
注意:driver
和 url
的变化
# mysql数据库连接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
注意:
1、这里的 url
使用了 ?serverTimezone=GMT%2B8
后缀,因为 Spring Boot 2.1
集成了 8.0
版本的 JDBC
驱动,
这个版本的 JDBC
驱动需要添加这个后缀,否则运行测试用例报告如下错误:
java.sql.SQLException: The server time zone value ‘Öйú±ê׼ʱ¼ä’ is unrecognized or representsmore
2、这里的 driver-class-name
使用了 com.mysql.cj.jdbc.Driver
,在 MySQL 8.x.x
中 建议使用这个驱动,之前的 com.mysql.jdbc.Driver
已经被废弃,否则运行测试用例的时候会有 WARN
信息。
5、编写代码
I、主类
在 Spring Boot 启动类中添加 @MapperScan
注解,扫描 Mapper
包。
注意:扫描的包名根据实际情况修改。
@SpringBootApplication
@MapperScan("com.yanghui.mybatisplus.mapper")
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
II、实体
创建包 entity
编写实体类 User.java
(此处使用了 Lombok
简化代码)
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
Lombok
使用参考:https://blog.youkuaiyun.com/motui/article/details/79012846
III、mapper
创建包 mapper 编写Mapper 接口
: UserMapper.java
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
6、开始使用
添加测试类,进行功能测试(使用 SpringBoot
的单元测试):
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void testSelectList(){
System.out.println(("----- selectAll method test ------"));
// UserMapper 中的 selectList() 方法的参数为 MP 内置的条件封装器 Wrapper
// 所以不填写就是无任何条件
List<User> list = userMapper.selectList(null);
list.forEach(System.out::println);
}
}
注意:
IDEA 在 userMapper
处报错,因为找不到注入的对象,因为类是动态创建的,但是程序可以正确的执行。
为了避免报错,可以在 Dao
层 的接口上添加 @Mapper
注解
控制台输出:
----- selectAll method test ------
User(id=1, name=Jone, age=18, email=test1@baomidou.com)
User(id=2, name=Jack, age=20, email=test2@baomidou.com)
User(id=3, name=Tom, age=28, email=test3@baomidou.com)
User(id=4, name=Sandy, age=21, email=test4@baomidou.com)
User(id=5, name=Billie, age=24, email=test5@baomidou.com)
通过以上几个简单的步骤,我们就实现了 User 表的 CRUD 功能,甚至连 XML 文件都不用编写!
7、配置日志
# SQL 日志输出到控制台
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
五、MyBatisPlus
的 CRUD
接口
1、insert
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void testInsert(){
User user = new User();
user.setAge(18);
user.setName("yh");
user.setEmail("121515454@qq.com");
int result = userMapper.insert(user);
System.out.println(result); //影响的行数
System.out.println(user); //id自动回填
}
注意:数据库插入id值默认为:全局唯一id
主键策略:
(1)ID_WORKER
MyBatis-Plus
默认的主键策略是: ID_WORKER
全局唯一 ID
参考资料:分布式系统唯一ID生成方案汇总:
https://www.cnblogs.com/haoxinyue/p/5208136.html
(2)自增策略
- 需要在创建数据表的时候设置
主键自增
- 实体字段中配置
@TableId(type = IdType.AUTO)
@Data
public class User {
@TableId(type = IdType.AUTO) //id自增
private Long id;
private String name;
private Integer age;
private String email;
}
要想影响所有实体的配置,可以设置全局主键配置:
# 全局设置主键生成策略
mybatis-plus.global-config.db-config.id-type=auto
其它主键策略:分析 IdType
源码可知:
@Getter
public enum IdType {
/**
* 数据库ID自增
*/
AUTO(0),
/**
* 该类型为未设置主键类型
*/
NONE(1),
/**
* 用户输入ID
* 该类型可以通过自己注册自动填充插件进行填充
*/
INPUT(2),
/* 以下3种类型、只有当插入对象ID 为空,才自动填充。 */
/**
* 全局唯一ID (idWorker)
*/
ID_WORKER(3),
/**
* 全局唯一ID (UUID)
*/
UUID(4),
/**
* 字符串全局唯一ID (idWorker 的字符串表示)
*/
ID_WORKER_STR(5);
private int key;
IdType(int key) {
this.key = key;
}
}
2、update
I、根据Id更新操作
注意:update
时生成的 sql
自动是动态 sql
:UPDATE user SET age=? WHERE id=?
@Test
void testUpdate(){
User user = new User();
user.setId(1L);
user.setAge(28);
int result = userMapper.updateById(user);
System.out.println(result);
}
II、自动填充
项目中经常会遇到一些数据,每次都使用相同的方式填充,例如记录的创建时间,更新时间
等。
我们可以使用 MyBatisPlus
的自动填充功能,完成这些字段的赋值工作:
(1)数据库表中添加自动填充字段
在User表中添加 datetime
类型的新的字段 create_time、update_time
.
(2)实体上添加注解
@Data
public class User {
@TableField(fill = FieldFill.INSERT)
private Date createTime;
// @TableField(fill = FieldFill.UPDATE)
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
(3)实现元对象处理器接口
注意:不要忘记添加 @Component
注解,驼峰命名
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(MyMetaObjectHandler.class);
// 使用 mp 实现添加操作,这个方法执行
// createTime 对应的是实体类中的属性,而不是数据库中的字段
@Override
public void insertFill(MetaObject metaObject) {
LOGGER.info("start insert fill。。。");
this.setFieldValByName("createTime", new Date(), metaObject);
this.setFieldValByName("updateTime", new Date(), metaObject);
}
// 使用 mp 实现修改操作,这个方法执行
@Override
public void updateFill(MetaObject metaObject) {
LOGGER.info("start update fill ....");
this.setFieldValByName("updateTime", new Date(), metaObject);
}
}
3、乐观锁
主要适用场景:当要更新一条记录的时候,希望这条记录没有被别人更新,也就是说实现线程安全的数据更新。
MVCC
、版本控制
乐观锁实现方式:
- 取出记录时,获取当前 version(版本号)
- 更新时,带上这个 version
- 执行更新时, set version = newVersion where version = oldVersion
- 如果 version 不对,就更新失败
在提交数据时,比较当前版本号和数据库版本号是否一致,一致可提交,并将版本号+1;不一致就提交失败
(1)数据库中添加 version 字段
ALTER TABLE `user` ADD COLUMN `version` INT
(2)实体类添加version字段
@Version
@TableField(fill = FieldFill.INSERT)
private Integer Version;
(3)元对象处理器接口添加version的insert默认值
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
//使用 mp 实现添加操作,这个方法执行
@Override
public void insertFill(MetaObject metaObject) {
...
this.setFieldValByName("version",1,metaObject);
}
}
特别说明:
支持的数据类型只有 int,Integer,long,Long,Date,Timestamp,LocalDateTime
整数类型下 newVersion = oldVersion + 1
newVersion 会回写到 entity 中
仅支持 updateById(id) 与 update(entity, wrapper) 方法
在 update(entity, wrapper) 方法下, wrapper 不能复用!!!
(4)在 MybatisPlusConfig
中注册 Bean,使用乐观锁插件
@EnableTransactionManagement
@Configuration
@MapperScan("com.achang.mybatisplus.mapper")
public class MybatisPlusConfig {
//乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
4、select
1、根据id查询记录
@Test
void testSelectById(){
User user = userMapper.selectById(1);
System.out.println(user);
}
2、通过多个id批量查询
完成了动态 sql
的 foreach
功能
//多个id批量查询
@Test
void testSelectBatchIds(){
//通过集合,批量查询数据
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
3、简单的条件查询
通过map封装查询条件
@Test
void testSelectByMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","guigu");
map.put("age",18);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
注意:
map中的key对应的是数据库中的列名
。例如数据库 user_id
,实体类是 userId
,这时map的key需要填写 user_id
5、分页
MyBatisPlus
自带分页插件,只要简单的配置即可实现分页功能。
(1)配置分页插件
//分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
(2)测试 selectPage
分页
测试:最终通过page对象获取相关数据
// 分页查询
@Test
void testPage(){
//1、创建 page 对象
//传入参数:当前页 和 每页显示记录数
Page<User> userPage = new Page<>(1,3);
// 调用 mp 分页查询方法
//调用 mp 分页查询过程中,底层会封装,把所有分页数据分装到 page 对象中
userMapper.selectPage(userPage,null);
//通过 page 对象获取数据
userPage.getRecords().forEach(System.out::println);// 遍历查询的分页数据
System.out.println(userPage.getCurrent());// 获取当前页
System.out.println(userPage.getSize());// 每页显示记录数
System.out.println(userPage.getTotal());// 总记录数
System.out.println(userPage.getPages());// 总页数
System.out.println(userPage.hasNext());// 判断是否有下一页
System.out.println(userPage.hasPrevious());// 判断是否有上一页
}
控制台sql语句打印:
SELECT id,name,age,email,create_time,update_time FROM user LIMIT 0,3
(3)测试 selectMapsPage
分页:结果集是 Map
// 测试selectMapsPage分页:结果集是Map
@Test
void testSelectMapsPage(){
// 1、创建page对象
// 传入参数:当前页 和 每页显示记录数
Page<User> page = new Page<>(1,3);
// 调用 mp 分页查询方法
// 调用 mp 分页查询过程中,底层会封装,把所有分页数据分装到 page 对象中
IPage<Map<String, Object>> mapIPage = userMapper.selectMapsPage(page, null);
//注意:此行必须使用 mapIPage 获取记录列表,否则会有数据类型转换错误
mapIPage.getRecords().forEach(System.out::println);
System.out.println(page.getCurrent());
System.out.println(page.getPages());
System.out.println(page.getSize());
System.out.println(page.getTotal());
System.out.println(page.hasNext());
System.out.println(page.hasPrevious());
}
6、delete
1、根据id删除记录
@Test
public void testDeleteById(){
int result = userMapper.deleteById(1364080977348956166L);
System.out.println(result);
}
2、批量删除
@Test
public void testDeleteById(){
int result = userMapper.deleteById(1364080977348956166L);
System.out.println(result);
}
3、简单的条件查询删除
@Test
public void testDeleteByMap() {
HashMap<String, Object> map = new HashMap<>();
map.put("name", "Helen");
map.put("age", 18);
int result = userMapper.deleteByMap(map);
System.out.println(result);
}
4、逻辑删除
- 物理删除:
真实删除
,将对应数据从数据库中删除,之后查询不到此条被删除数据。 - 逻辑删除:
假删除
,将对应数据中代表是否被删除字段状态修改为“被删除状态”,之后在数据库中仍
旧能看到此条数据记录。
(1)数据库中添加 deleted
字段
ALTER TABLE `user` ADD COLUMN `deleted` boolean
(2)实体类添加 deleted
字段
并加上 @TableLogic
注解 和 @TableField(fill = FieldFill.INSERT)
注解
@TableLogic
@TableField(fill = FieldFill.INSERT)
private Integer deleted;
(3)元对象处理器接口添加 deleted
的 insert
默认值
@Override
public void insertFill(MetaObject metaObject) {
......
this.setFieldValByName("deleted", 0, metaObject);
}
(4)application.properties
加入配置
此为默认值,如果你的默认值和 mp 默认的一样 , 该配置可无,指定删除为1,没删为0
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
(5)在 MybatisPlusConfig
中注册 Bean
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
(6)测试逻辑删除
- 测试后发现,数据并没有被删除,deleted字段的值由
0变成了1
- 测试后分析打印的sql语句,是一条update
- 注意:被删除数据的deleted 字段的值必须是 0,才能被选取出来执行逻辑删除的操作
/**
* 测试 逻辑删除
*/
@Test
public void testLogicDelete() {
int result = userMapper.deleteById(1L);
System.out.println(result);
}
(7)测试逻辑删除后的查询
MyBatisPlus
中查询操作也会自动添加逻辑删除字段的判断
/**
* 测试 逻辑删除后的查询:
* 不包括被逻辑删除的记录
*/
@Test
public void testLogicDeleteSelect() {
User user = new User();
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
测试后分析打印的 sql 语句,包含 WHERE deleted=0
SELECT id,name,age,email,create_time,update_time,deleted FROM user WHERE deleted=0
7、性能分析
性能分析拦截器,用于输出每条 SQL
语句及其执行时间
SQL
性能执行分析,开发环境使用,超过指定时间,停止运行。有助于发现问题
I、配置插件
(1)参数说明
参数:maxTime
: SQL
执行最大时长,超过自动停止运行,有助于发现问题。
参数:format
: SQL
是否格式化,默认 false
。
(2)在 MybatisPlusConfig
中配置
开发环境使用,线上不推荐
。
//性能分析插件
/**
* SQL 执行性能分析插件
* 开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长
*/
@Bean
@Profile({"dev","test"})// 设置 dev test 环境开启
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(100);//ms,超过此处设置的ms则sql不执行
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
(3)SpringBoot
中设置 dev
环境
#环境设置:dev、test、prod
spring.profiles.active=dev
可以针对各环境新建不同的配置文件
application-dev.properties
、application-test.properties
、application-prod.properties
也可以自定义环境名称:如 test1
、test2
II、测试
(1)常规测试
/**
* 测试 性能分析插件
*/
@Test
public void testPerformance() {
User user = new User();
user.setName("我是Helen");
user.setEmail("helen@sina.com");
user.setAge(18);
userMapper.insert(user);
}
(2)将 maxTime
改小之后再次进行测试
// ms,超过此处设置的 ms 不执行
performanceInterceptor.setMaxTime(5);
如果执行时间过长,则抛出异常:The SQL execution time is too large
8、其它
如果想进行复杂条件查询,那么需要使用条件构造器 Wrapper
,涉及到如下方法
1、delete
2、selectOne
3、selectCount
4、selectList
5、selectMaps
6、selectObjs
7、update
六、MyBatisPlus
条件构造器 Wrapper
1、Wrapper
介绍
Wrapper : 条件构造抽象类,最顶端父类
AbstractWrapper : 用于查询条件封装,生成 sql 的 where 条件
QueryWrapper : Entity 对象封装操作类,不是用lambda语法【推荐使用】
UpdateWrapper : Update 条件封装,用于Entity对象更新操作
AbstractLambdaWrapper : Lambda 语法使用 Wrapper统一处理解析 lambda 获取 column。
LambdaQueryWrapper :看名称也能明白就是用于Lambda语法使用的查询Wrapper
LambdaUpdateWrapper : Lambda 更新封装Wrapper
2、AbstractWrapper
注意:以下条件构造器的方法入参中的 column 均表示数据库字段
1、ge
、gt
、le
、lt
、isNull
、isNotNull
@Test
public void testDelete() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
// 链式编程
queryWrapper.isNull("name")
.ge("age", 12)
.isNotNull("email");
int result = userMapper.delete(queryWrapper);
System.out.println("delete return count = " + result);
}
sql
:
UPDATE user SET deleted=1 WHERE deleted=0 AND name IS NULL AND age >= ? AND email IS NOT NULL
2、eq
、ne
注意:seletOne
返回的是一条实体记录,当出现多条时会报错
@Test
public void testSelectOne() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", "Tom");
User user = userMapper.selectOne(queryWrapper);
System.out.println(user);
}
sql
:
SELECT id,name,age,email,create_time,update_time,version,deleted FROM user WHERE deleted=0 AND name = ?
3、between
、notBetween
包含大小边界
@Test
public void testSelectCount() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.between("age", 20, 30);
Integer count = userMapper.selectCount(queryWrapper);
System.out.println(count);
}
sql
:
SELECT COUNT(1) FROM user WHERE deleted=0 AND age BETWEEN ? AND ?
4、allEq
@Test
public void testSelectList() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
Map<String, Object> map = new HashMap<>();
map.put("id", 2);
map.put("name", "Jack");
map.put("age", 20);
queryWrapper.allEq(map);
List<User> users = userMapper.selectList(queryWrapper);
users.forEach(System.out::println);
}
sql:
SELECT id,name,age,email,create_time,update_time,version,deleted FROM user WHERE deleted=0 AND name = ? AND id = ? AND age = ?
5、like
、notLike
、likeLeft
、likeRight
selectMaps
返回 Map
集合列表
@Test
public void testSelectMaps() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.notLike("name", "e")
.likeRight("email", "t");
List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);//返回值是Map列表
maps.forEach(System.out::println);
}
sql
:
SELECT id,name,age,email,create_time,update_time,version,deleted FROM user WHERE deleted=0 AND name NOT LIKE ? AND email LIKE ?
6、in
、notIn
、inSql
、notinSql
、exists
、notExists
in
、notIn
:
-
notIn(“age”,{1,2,3})—>age not in (1,2,3)
-
notIn(“age”, 1, 2, 3)—>age not in (1,2,3)
inSql、notinSql:可以实现子查询
-
例:
inSql(“age”, “1,2,3,4,5,6”)—>age in (1,2,3,4,5,6)
-
例:
inSql(“id”, “select id from table where id < 3”)—>id in (select id from table where id < 3)
@Test
public void testSelectObjs() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
// queryWrapper.in("id", 1, 2, 3);
queryWrapper.inSql("id", "select id from user where id < 3");
// 返回值是 Object 集合
List<Object> objects = userMapper.selectObjs(queryWrapper);
objects.forEach(System.out::println);
}
sql
:
SELECT id,name,age,email,create_time,update_time,version,deleted FROM user WHERE deleted=0 AND id IN (select id from user where id < 3)
7、or
、and
注意:这里使用的是 UpdateWrapper
不调用 or
则默认为使用 and
连接
@Test
public void testUpdate1() {
//修改值
User user = new User();
user.setAge(99);
user.setName("Andy");
//修改条件
UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
userUpdateWrapper
.like("name", "h")
.or()
.between("age", 20, 30);
int result = userMapper.update(user, userUpdateWrapper);
System.out.println(result);
}
sql
:
UPDATE user SET name=?, age=?, update_time=? WHERE deleted=0 AND name LIKE ? OR age BETWEEN ? AND ?
8、嵌套 or
、嵌套 and
@Test
public void testUpdate2() {
// 修改值
User user = new User();
user.setAge(99);
user.setName("Andy");
// 修改条件
UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
userUpdateWrapper.like("name", "h")
.or(i -> i.eq("name", "李白").ne("age", 20));
int result = userMapper.update(user, userUpdateWrapper);
System.out.println(result);
}
sql
:
UPDATE user SET name=?, age=?, update_time=? WHERE deleted=0 AND name LIKE ? OR ( name = ? AND age <> ? )
10、last
直接拼接到 sql
语句 的最后
注意:只能调用一次,多次调用以最后一次为准 有 sql
注入的风险,请谨慎使用
@Test
public void testSelectListLast() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.last("limit 1");
List<User> users = userMapper.selectList(queryWrapper);
users.forEach(System.out::println);
}
sql
:
SELECT id,name,age,email,create_time,update_time,version,deleted FROM user WHERE deleted=0 limit 1
11、指定要查询的列
@Test
public void testSelectListColumn() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select("id", "name", "age");
List<User> users = userMapper.selectList(queryWrapper);
users.forEach(System.out::println);
}
sql:
SELECT id,name,age FROM user WHERE deleted=0
12、set
、setSql
最终的 sql
会合并 user.setAge()
,以及 userUpdateWrapper.set()
和 setSql()
中 的字段
@Test
public void testUpdateSet() {
//修改值
User user = new User();
user.setAge(99);
//修改条件
UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
userUpdateWrapper.like("name", "h")
.set("name", "老李头")// 除了可以查询还可以使用set设置修改的字段
.setSql(" email = '123@qq.com'");// 可以有子查询
int result = userMapper.update(user, userUpdateWrapper);
}
sql
:
UPDATE user SET age=?, update_time=?, name=?, email = '123@qq.com' WHERE deleted=0 AND name LIKE ?