简介
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
官网:https://mp.baomidou.com/
特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作
框架结构
快速上手
基于官网https://mp.baomidou.com/guide/quick-start.html#%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B7%A5%E7%A8%8B
进行编写
1:新建数据库
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)
);
插入数据
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:初始化项目
新建一个springboot项目,导入相应的依赖
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wxf</groupId>
<artifactId>mybatis_plus</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatis_plus</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--mybatis-plus依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
这里特别注意,mybatis依赖和mybatis-plus依赖不能同时导入,不然会报错。只能二选一
配置文件
# mysql 5 驱动不同 com.mysql.jdbc.Driver
# mysql 8 驱动不同com.mysql.cj.jdbc.Driver、需要增加时区的配置 serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
创建相应的pojo
package com.wxf.mybatis_plus.pojo;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
创建mapper接口
package com.wxf.mybatis_plus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wxf.mybatis_plus.pojo.User;
import org.springframework.stereotype.Repository;
// 在对应的Mapper上面继承基本的类 BaseMapper
@Repository// 代表持久层
public interface UserMapper extends BaseMapper<User> {
// 所有的CRUD操作都已经编写完成了
// 不需要像以前的配置一大堆文件了!
}
在启动类上添加包的扫描
package com.wxf.mybatis_plus;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.wxf.mybatis_plus.mapper")
@SpringBootApplication
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
3:测试demo
package com.wxf.mybatis_plus;
import com.wxf.mybatis_plus.mapper.UserMapper;
import com.wxf.mybatis_plus.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class MybatisPlusApplicationTests {
// 继承了BaseMapper,所有的方法都来自己父类
// 也可以编写自己的扩展方法!
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
// 参数是一个 Wrapper ,条件构造器
// 查询全部用户
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5f5effb0] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1045336031 wrapping com.mysql.cj.jdbc.ConnectionImpl@6a1d6ef2] will not be managed by Spring
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5f5effb0]
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)
Process finished with exit code 0
测试运行成功,没有写一行xml和sql,就能成功运行一个查询。
如果想查看sql语句,可以配置一下日志的输出。
#配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
这里先让控制台输出,也可以导入依赖用其他日志的形式进行输出打印记录。
输出如下
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5f5effb0] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1045336031 wrapping com.mysql.cj.jdbc.ConnectionImpl@6a1d6ef2] will not be managed by Spring
==> Preparing: SELECT id,name,age,email,create_time AS create_time,update_time AS update_time FROM user
==> Parameters:
<== Columns: id, name, age, email, create_time, update_time
<== Row: 1, Jone, 18, test1@baomidou.com, null, null
<== Row: 2, Jack, 20, test2@baomidou.com, null, null
<== Row: 3, Tom, 28, test3@baomidou.com, null, null
<== Row: 4, Sandy, 21, test4@baomidou.com, null, null
<== Row: 5, Billie, 24, test5@baomidou.com, null, null
<== Total: 5
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5f5effb0]
User(id=1, name=Jone, age=18, email=test1@baomidou.com, create_time=null, update_time=null)
User(id=2, name=Jack, age=20, email=test2@baomidou.com, create_time=null, update_time=null)
User(id=3, name=Tom, age=28, email=test3@baomidou.com, create_time=null, update_time=null)
User(id=4, name=Sandy, age=21, email=test4@baomidou.com, create_time=null, update_time=null)
User(id=5, name=Billie, age=24, email=test5@baomidou.com, create_time=null, update_time=null)
可以看到mybatis-plus已经为我们编写出了基础的sql,没必要去花时间去写那些千篇一律的sql,可以把自己的着重点放在一些复杂业务逻辑的处理上。聪儿大大提高我们的工作效率。
CRUD扩展
测试insert
@Test
void insert() {
User user = new User();
user.setAge(23);
user.setName("xf");
user.setEmail("123@qq.com");
int insert = userMapper.insert(user); // 帮我们自动生成id
System.out.println(insert);// 受影响的行数
System.out.println(user);// 发现,id会自动回填
}
运行结果如下
==> Preparing: INSERT INTO user ( id, name, age, email, create_time ) VALUES ( ?, ?, ?, ?, ? )
==> Parameters: 1401810500687790082(Long), xf(String), 23(Integer), 123@qq.com(String), null
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@421def93]
1
User(id=1401810500687790082, name=xf, age=23, email=123@qq.com, create_time=null, update_time=null)
发现自动生成了一个uuid,可见mybatis-plus内置了一套id生成策略
分布式系统唯一id生成:https://www.cnblogs.com/haoxinyue/p/5208136.html
mybatis-plus内置的uuid生成策略就是雪花算法
雪花算法
snowflflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。可以保证几乎全球唯一!
主键自增
//对应数据库中的主键(uuid,自增id,)
@TableId(type = IdType.AUTO)
private Long id;
实体类上加上注解。与此同时数据库也需要设置主键自增
==> Preparing: INSERT INTO user ( name, age, email, create_time ) VALUES ( ?, ?, ?, ? )
==> Parameters: xf(String), 23(Integer), 123@qq.com(String), null
<== Updates: 1
源代码分析
/*
* Copyright (c) 2011-2020, hubin (jobob@qq.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baomidou.mybatisplus.annotation;
import lombok.Getter;
/**
* <p>
* 生成ID类型枚举类
* </p>
*
* @author hubin
* @since 2015-11-10
*/
@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;
}
}
测试更新
@Test
void testupdate() {
User user = new User();
user.setId(5L);
user.setName("rouse");
user.setAge(30);
int i = userMapper.updateById(user);
}
更新代码如下
JDBC Connection [HikariProxyConnection@1700751834 wrapping com.mysql.cj.jdbc.ConnectionImpl@43b5021c] will not be managed by Spring
==> Preparing: UPDATE user SET name=?, age=?, update_time=? WHERE id=?
==> Parameters: rouse(String), 30(Integer), null, 5(Long)
<== Updates: 1
可以发现,这里直接帮我们进行了动态的配置。动态sql的各种if,else判定都不需要写了
自动填充
创建时间、修改时间!这些个操作一遍都是自动化完成的,我们不希望手动更新!
阿里巴巴开发手册:所有的数据库表:gmt_create、gmt_modifified几乎所有的表都要配置上!而且需要自动化!
方式一:数据库级别(工作中如果修改生产数据库,那是有很大风险的,而且不规范)
设置数据库字段默认值,为当前的时间就行
方式二:代码级别
1:实体类字段属性上需要增加注解
新增如下两个字段
@TableField(fill = FieldFill.INSERT)
private Date create_time;
@TableField(fill = FieldFill.UPDATE)
private Date update_time;
新建一个handler文件夹,添加一个配置类
package com.wxf.mybatis_plus.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
@Slf4j
@Component // 一定不要忘记把处理器加到IOC容器中!
public class MyMetaObjectHandler implements MetaObjectHandler {
// 插入时的填充策略
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill.....");
// setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject
this.setFieldValByName("create_time",new Date(),metaObject);
this.setFieldValByName("update_time",new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill.....");
this.setFieldValByName("update_time",new Date(),metaObject);
}
}
这时候再添加,或者修改会发现,创建时间和修改时间字段已经自动填入当前的时间了,再也没有必要像以前那样还要去手动获取当前时间,再set值,方便了很多,可以精简代码。
乐观锁
乐观锁 : 故名思意十分乐观,它总是认为不会出现问题,无论干什么不去上锁!如果出现了问题,再次更新值测试
悲观锁:故名思意十分悲观,它总是认为总是出现问题,无论干什么都会上锁!再去操作!
乐观锁实现方式:
- 取出记录时,获取当前 version
- 更新时,带上这个version
- 执行更新时, set version = newVersion where version = oldVersion
- 如果version不对,就更新失败
乐观锁:1、先查询,获得版本号 version = 1
-- A
update user set name = "www", version = version + 1 where id = 2 and version = 1
-- B 线程抢先完成,这个时候 version = 2,会导致 A 修改失败!
update user set name = "www", version = version + 1 where id = 2 and version = 1
在mybatis-plus中也可以实现乐观锁
1:在数据库中新建version字段
在实体类里面也新加一个字段
@Version //乐观锁Version注解
private Integer version;
添加一个测试方法
// 测试乐观锁成功!
@Test
void testleguans() {
// 1、查询用户信息
User user = userMapper.selectById(1L);
user.setAge(30);
int i = userMapper.updateById(user);
}
查看返回结果
JDBC Connection [HikariProxyConnection@380556447 wrapping com.mysql.cj.jdbc.ConnectionImpl@2525a5b8] will not be managed by Spring
==> Preparing: UPDATE user SET name=?, age=?, email=?, update_time=?, version=? WHERE id=? AND version=?
==> Parameters: Jone(String), 30(Integer), test1@baomidou.com(String), 2021-06-07 17:10:23.099(Timestamp), 2(Integer), 1(Long), 1(Integer)
<== Updates: 1
发现version自增了。
测试乐观锁失败
@Test
void testleguans2() {
// 1、查询用户信息
// 线程 1
User user = userMapper.selectById(1L);
user.setAge(30);
user.setEmail("1295@123.com");
// 模拟另外一个线程执行了插队操作
User user2 = userMapper.selectById(1L);
user2.setAge(10);
user2.setEmail("12935@123.com");
userMapper.updateById(user2);
// 自旋锁来多次尝试提交!
int i = userMapper.updateById(user);// 如果没有乐观锁就会覆盖插队线程的值!
}
这时查看数据库发现
1 Jone 10 12935@123.com 2021-06-08 09:15:21 3
生效的是第二个更新操作,因为第二个先修改了,version的值发生了变化,所以第一个更新会失效
查询
@Test
void testselect() {
//根据多个id批量查询
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
==> Preparing: SELECT id,name,age,email,create_time AS create_time,update_time AS update_time,version FROM user WHERE id IN ( ? , ? , ? )
==> Parameters: 1(Integer), 2(Integer), 3(Integer)
<== Columns: id, name, age, email, create_time, update_time, version
<== Row: 1, Jone, 10, 12935@123.com, null, 2021-06-08 09:15:21, 3
<== Row: 2, Jack, 20, test2@baomidou.com, null, null, 1
<== Row: 3, Tom, 28, test3@baomidou.com, null, null, 1
<== Total: 3
@Test
void testselect2() {
//根据map条件查询
HashMap<String, Object> map = new HashMap<>();
map.put("name","xf");
map.put("age",12);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
==> Parameters: xf(String), 12(Integer)
<== Columns: id, name, age, email, create_time, update_time, version
<== Row: 1401729476087787521, xf, 12, 123@qq.com, null, null, 1
<== Row: 1401768881641046018, xf, 12, 123@qq.com, null, null, 1
<== Total: 2
删除
@Test
void testdelete() {
//根据id删除
int i = userMapper.deleteById(1401729476087787521L);
System.out.println(i);
}
@Test
void testdelete2() {
//根据多个id批量删除
int i = userMapper.deleteBatchIds(Arrays.asList(1401810500687790084L,1401810500687790083l));
System.out.println(i);
}
@Test
void testdelete3() {
//根据MAP删除
HashMap<String, Object> map = new HashMap<>();
map.put("name","xf");
map.put("age",12);
int i = userMapper.deleteByMap(map);
System.out.println(i);
}
物理删除 :从数据库中直接移除
逻辑删除 :再数据库中没有被移除,而是通过一个变量来让他失效! deleted = 0 => deleted = 1
管理员可以查看被删除的记录!防止数据的丢失,类似于回收站!
测试:
1:首先在数据库新建一个deleted字段,用来表示是否删除,1表示已经删除0表示未删除
2:实体类中新增属性
@TableLogic //逻辑删除
private Integer deleted;
3:配置类中新增一个bean
// 逻辑删除组件!
@Bean
public ISqlInjector sqlInjector() { return new LogicSqlInjector(); }
4:配置中新增
# 配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
再来测试删除发现deleted中字段变为1了。就代表着删除了。
JDBC Connection [HikariProxyConnection@307036850 wrapping com.mysql.cj.jdbc.ConnectionImpl@3451f01d] will not be managed by Spring
==> Preparing: UPDATE user SET deleted=1 WHERE id=? AND deleted=0
==> Parameters: 1(Long)
<== Updates: 1
性能分析插件
作用:性能分析拦截器,用于输出每条 SQL 语句及其执行时间
MP也提供性能分析插件,如果超过这个时间就停止运行!
1:在配置类中,导入插件
/**
* SQL执行效率插件
*/
@Bean
@Profile({"dev", "test"})// 设置 dev test 环境开启,保证我们的效率
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(1); // ms设置sql执行的最大时间,如果超过了则不 执行
performanceInterceptor.setFormat(true); // 是否格式化代码
return performanceInterceptor;
}
2:在配置类中设置开发环境
spring.profiles.active=dev
3:执行一个查询
Time:26 ms - ID:com.wxf.mybatis_plus.mapper.UserMapper.selectList
Execute SQL:
SELECT
id,
name,
age,
email,
create_time AS create_time,
update_time AS update_time,
version,
deleted
FROM
user
WHERE
deleted=0
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@655f69da]
这里只要查询的时间超过,设置的时间就会不执行,会抛出异常。
条件构造器
写一些复杂的sql就可以使用它来替代!
测试
@Test
void test() {
// 查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于12
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.isNotNull("name").isNotNull("email").ge("age",12);
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
执行如下
Time:55 ms - ID:com.wxf.mybatis_plus.mapper.UserMapper.selectList
Execute SQL:
SELECT
id,
name,
age,
email,
create_time AS create_time,
update_time AS update_time,
version,
deleted
FROM
user
WHERE
deleted=0
AND name IS NOT NULL
AND email IS NOT NULL
AND age >= 12
User(id=2, name=Jack, age=20, email=test2@baomidou.com, create_time=null, update_time=null, version=1, deleted=0)
User(id=3, name=Tom, age=28, email=test3@baomidou.com, create_time=null, update_time=null, version=1, deleted=0)
User(id=4, name=Sandy, age=21, email=test4@baomidou.com, create_time=null, update_time=null, version=1, deleted=0)
User(id=5, name=rouse, age=30, email=test5@baomidou.com, create_time=null, update_time=null, version=1, deleted=0)
User(id=1401810500687790082, name=xf, age=23, email=123@qq.com, create_time=null, update_time=null, version=1, deleted=0)
模糊查询
@Test
void test2() {
// 根据名字模糊查询
QueryWrapper<User> wrapper = new QueryWrapper<>();
QueryWrapper<User> like = wrapper.like("name", "xf");
userMapper.selectList(like).forEach(System.out::println);
}
区间查询
@Test
void test3() {
// 查询年龄在 20 ~ 30 岁之间的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
QueryWrapper<User> age = wrapper.between("age", 0, 30);
Integer integer = userMapper.selectCount(age);
System.out.println(integer);
}
模糊查询,以xxx开头
//模糊查询,以xxx开头
@Test
void test4() {
// 模糊查询,以xxx开头
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.notLike("name","a").likeLeft("name","f");
userMapper.selectList(wrapper).forEach(System.out::println);
}
子查询
//子查询
@Test
void test5() {
// 子查询
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.inSql("id","select id from user where id<3");
userMapper.selectList(wrapper).forEach(System.out::println);
}
排序
//排序
@Test
void test7() {
// 子查询
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.orderByDesc("id");
userMapper.selectList(wrapper).forEach(System.out::println);
}
常用注解
注解 | 说明 |
---|---|
@TableName | 描述:表名注解属性:value ☞ 表名 schema ☞ schema keepGlobalPrefix ☞ 是否保持使用全局的 tablePrefix 的值,默认值 false(如果设置了全局 tablePrefix 且自行设置了 value 的值) resultMap ☞ xml 中 resultMap 的 id autoResultMap ☞ 是否自动构建 resultMap 并使用,默认值 false(如果设置 resultMap 则不会进行 resultMap 的自动构建并注入) |
@TableId | 描述:主键注解属性:value ☞ 主键字段名 type ☞ 主键类型,默认值 IdType.NONE AUTO:数据库ID自增 NONE:无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT) INPUT:insert 前自行 set 主键值 ASSIGN_ID:分配ID(主键类型为 Number 或 String,使用接口 IdentifierGenerator 的方法 nextId (默认雪花算法) ASSIGN_UUID:分配 UUID,主键类型为 String,使用接口 IdentifierGenerator 的方法 nextUUID(默认 default 方法) |
@TableField | 描述:字段注解(非主键)属性:value ☞ 数据库字段名 el ☞ 映射为原生 #{ … } 逻辑,相当于写在 xml 里的 #{ … } 部分 exist ☞ 是否为数据库表字段,默认 true condition ☞ 字段 where 实体查询比较条件,有值设置则按设置的值为准,没有则为默认全局的 %s=#{%s} update ☞ 字段 update set 部分注入, 例如:update="%s+1" 表示更新时会 set version=version+1(该属性优先级高于 el 属性) select ☞ 是否进行 select 查询,默认 true keepGlobalFormat ☞ 是否保持使用全局的 format 进行处理,默认 false jdbcType ☞ JDBC 类型,默认 JdbcType.UNDEFINED (该默认值不代表会按照该值生效) typeHandler ☞ 类型处理器,默认 UnknownTypeHandler.class (该默认值不代表会按照该值生效) numericScale ☞ 指定小数点后保留的位数 |