mybatis-plus是一款Mybatis加强工具,用于简化开发,提升效率。下文使用缩写mp来简化表示mybatis-plus,本文主要介绍mp搭配SpringBoot的使用。java
注:本文使用的mp版本是当前最新的3.4.2,早期版本的差别请自行查阅文档mysql
官方网站:baomidou.com/算法
<!-- pom.xml --> <?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.3.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>mybatis-plus</artifactId> <version>0.0.1-SNAPSHOT</version> <name>mybatis-plus</name> <properties> <java.version>1.8</java.version> </properties> <dependencies> <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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
# application.yml spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/yogurt?serverTimezone=Asia/Shanghai username: root password: root mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #开启SQL语句打印
package com.example.mp.po; import lombok.Data; import java.time.LocalDateTime; @Data public class User { private Long id; private String name; private Integer age; private String email; private Long managerId; private LocalDateTime createTime; }
package com.example.mp.mappers; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.mp.po.User; public interface UserMapper extends BaseMapper<User> { }
package com.example.mp; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.example.mp.mappers") public class MybatisPlusApplication { public static void main(String[] args) { SpringApplication.run(MybatisPlusApplication.class, args); } }
DROP TABLE IF EXISTS user; CREATE TABLE user ( id BIGINT(20) PRIMARY KEY NOT NULL COMMENT '主键', name VARCHAR(30) DEFAULT NULL COMMENT '姓名', age INT(11) DEFAULT NULL COMMENT '年龄', email VARCHAR(50) DEFAULT NULL COMMENT '邮箱', manager_id BIGINT(20) DEFAULT NULL COMMENT '直属上级id', create_time DATETIME DEFAULT NULL COMMENT '建立时间', CONSTRAINT manager_fk FOREIGN KEY(manager_id) REFERENCES user (id) ) ENGINE=INNODB CHARSET=UTF8; INSERT INTO user (id, name, age ,email, manager_id, create_time) VALUES (1, '大BOSS', 40, 'boss@baomidou.com', NULL, '2021-03-22 09:48:00'), (2, '李经理', 40, 'boss@baomidou.com', 1, '2021-01-22 09:48:00'), (3, '黄主管', 40, 'boss@baomidou.com', 2, '2021-01-22 09:48:00'), (4, '吴组长', 40, 'boss@baomidou.com', 2, '2021-02-22 09:48:00'), (5, '小菜', 40, 'boss@baomidou.com', 2, '2021-02-22 09:48:00')
package com.example.mp; import com.example.mp.mappers.UserMapper; import com.example.mp.po.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest public class SampleTest { @Autowired private UserMapper mapper; @Test public void testSelect() { List<User> list = mapper.selectList(null); assertEquals(5, list.size()); list.forEach(System.out::println); } }
准备工做完成spring
数据库状况以下sql
项目目录以下数据库
运行测试类express
能够看到,针对单表的基本CRUD操做,只须要建立好实体类,并建立一个继承自BaseMapper
的接口便可,可谓很是简洁。而且,咱们注意到,User
类中的managerId
,createTime
属性,自动和数据库表中的manager_id
,create_time
对应了起来,这是由于mp自动作了数据库下划线命名,到Java类的驼峰命名之间的转化。apache
mp一共提供了8个注解,这些注解是用在Java的实体类上面的。数组
@TableName
安全
注解在类上,指定类和数据库表的映射关系。实体类的类名(转成小写后)和数据库表名相同时,能够不指定该注解。
@TableId
注解在实体类的某一字段上,表示这个字段对应数据库表的主键。当主键名为id时(表中列名为id,实体类中字段名为id),无需使用该注解显式指定主键,mp会自动关联。若类的字段名和表的列名不一致,可用value
属性指定表的列名。另,这个注解有个重要的属性type
,用于指定主键策略。
@TableField
注解在某一字段上,指定Java实体类的字段和数据库表的列的映射关系。这个注解有以下几个应用场景。
排除非表字段
若Java实体类中某个字段,不对应表中的任何列,它只是用于保存一些额外的,或组装后的数据,则能够设置exist
属性为false
,这样在对实体对象进行插入时,会忽略这个字段。排除非表字段也能够经过其余方式完成,如使用static
或transient
关键字,但我的以为不是很合理,不作赘述
字段验证策略
经过insertStrategy
,updateStrategy
,whereStrategy
属性进行配置,能够控制在实体对象进行插入,更新,或做为WHERE条件时,对象中的字段要如何组装到SQL语句中。
字段填充策略
经过fill
属性指定,字段为空时会进行自动填充
@Version
乐观锁注解
@EnumValue
注解在枚举字段上
@TableLogic
逻辑删除
KeySequence
序列主键策略(oracle
)
InterceptorIgnore
插件过滤规则
mp封装了一些最基础的CRUD方法,只须要直接继承mp提供的接口,无需编写任何SQL,便可食用。mp提供了两套接口,分别是Mapper CRUD接口和Service CRUD接口。而且mp还提供了条件构造器Wrapper
,能够方便地组装SQL语句中的WHERE条件。
只需定义好实体类,而后建立一个接口,继承mp提供的BaseMapper
,便可食用。mp会在mybatis启动时,自动解析实体类和表的映射关系,并注入带有通用CRUD方法的mapper。BaseMapper
里提供的方法,部分列举以下:
insert(T entity)
插入一条记录deleteById(Serializable id)
根据主键id删除一条记录delete(Wrapper<T> wrapper)
根据条件构造器wrapper进行删除selectById(Serializable id)
根据主键id进行查找selectBatchIds(Collection idList)
根据主键id进行批量查找selectByMap(Map<String,Object> map)
根据map中指定的列名和列值进行等值匹配查找selectMaps(Wrapper<T> wrapper)
根据 wrapper 条件,查询记录,将查询结果封装为一个Map,Map的key为结果的列,value为值selectList(Wrapper<T> wrapper)
根据条件构造器wrapper
进行查询update(T entity, Wrapper<T> wrapper)
根据条件构造器wrapper
进行更新updateById(T entity)
下面讲解几个比较特别的方法
BaseMapper
接口还提供了一个selectMaps
方法,这个方法会将查询结果封装为一个Map,Map的key为结果的列,value为值
该方法的使用场景以下:
只查部分列
当某个表的列特别多,而SELECT的时候只须要选取个别列,查询出的结果也不必封装成Java实体类对象时(只查部分列时,封装成实体后,实体对象中的不少属性会是null),则能够用selectMaps
,获取到指定的列后,再自行进行处理便可
好比
@Test public void test3() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.select("id","name","email").likeRight("name","黄"); List<Map<String, Object>> maps = userMapper.selectMaps(wrapper); maps.forEach(System.out::println); }
进行数据统计
好比
// 按照直属上级进行分组,查询每组的平均年龄,最大年龄,最小年龄 /** select avg(age) avg_age ,min(age) min_age, max(age) max_age from user group by manager_id having sum(age) < 500; **/ @Test public void test3() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.select("manager_id", "avg(age) avg_age", "min(age) min_age", "max(age) max_age") .groupBy("manager_id").having("sum(age) < {0}", 500); List<Map<String, Object>> maps = userMapper.selectMaps(wrapper); maps.forEach(System.out::println); }
只会返回第一个字段(第一列)的值,其余字段会被舍弃
好比
@Test public void test3() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.select("id", "name").like("name", "黄"); List<Object> objects = userMapper.selectObjs(wrapper); objects.forEach(System.out::println); }
获得的结果,只封装了第一列的id
查询知足条件的总数,注意,使用这个方法,不能调用QueryWrapper
的select
方法设置要查询的列了。这个方法会自动添加select count(1)
好比
@Test public void test3() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.like("name", "黄"); Integer count = userMapper.selectCount(wrapper); System.out.println(count); } 复制代码
另一套CRUD是Service层的,只须要编写一个接口,继承IService
,并建立一个接口实现类,便可食用。(这个接口提供的CRUD方法,和Mapper接口提供的功能大同小异,比较明显的区别在于IService
支持了更多的批量化操做,如saveBatch
,saveOrUpdateBatch
等方法。
食用示例以下
IService
package com.example.mp.service; import com.baomidou.mybatisplus.extension.service.IService; import com.example.mp.po.User; public interface UserService extends IService<User> { }
ServiceImpl
,最后打上@Service
注解,注册到Spring容器中,便可食用package com.example.mp.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.mp.mappers.UserMapper; import com.example.mp.po.User; import com.example.mp.service.UserService; import org.springframework.stereotype.Service; @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { }
package com.example.mp; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.example.mp.po.User; import com.example.mp.service.UserService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class ServiceTest { @Autowired private UserService userService; @Test public void testGetOne() { LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery(); wrapper.gt(User::getAge, 28); User one = userService.getOne(wrapper, false); // 第二参数指定为false,使得在查到了多行记录时,不抛出异常,而返回第一条记录 System.out.println(one); } }
另,IService
也支持链式调用,代码写起来很是简洁,查询示例以下
@Test public void testChain() { List<User> list = userService.lambdaQuery() .gt(User::getAge, 39) .likeRight(User::getName, "王") .list(); list.forEach(System.out::println); }
更新示例以下
@Test public void testChain() { userService.lambdaUpdate() .gt(User::getAge, 39) .likeRight(User::getName, "王") .set(User::getEmail, "w39@baomidou.com") .update(); }
删除示例以下
@Test public void testChain() { userService.lambdaUpdate() .like(User::getName, "青蛙") .remove(); }
mp让我以为极其方便的一点在于其提供了强大的条件构造器Wrapper
,能够很是方便的构造WHERE条件。条件构造器主要涉及到3个类,AbstractWrapper
。QueryWrapper
,UpdateWrapper
,它们的类关系以下
在AbstractWrapper
中提供了很是多的方法用于构建WHERE条件,而QueryWrapper
针对SELECT
语句,提供了select()
方法,可自定义须要查询的列,而UpdateWrapper
针对UPDATE
语句,提供了set()
方法,用于构造set
语句。条件构造器也支持lambda表达式,写起来很是舒爽。
下面对AbstractWrapper
中用于构建SQL语句中的WHERE条件的方法进行部分列举
eq
:equals,等于allEq
:all equals,全等于ne
:not equals,不等于gt
:greater than ,大于 >
ge
:greater than or equals,大于等于≥
lt
:less than,小于<
le
:less than or equals,小于等于≤
between
:至关于SQL中的BETWEENnotBetween
like
:模糊匹配。like("name","黄")
,至关于SQL的name like '%黄%'
likeRight
:模糊匹配右半边。likeRight("name","黄")
,至关于SQL的name like '黄%'
likeLeft
:模糊匹配左半边。likeLeft("name","黄")
,至关于SQL的name like '%黄'
notLike
:notLike("name","黄")
,至关于SQL的name not like '%黄%'
isNull
isNotNull
in
and
:SQL链接符ANDor
:SQL链接符ORapply
:用于拼接SQL,该方法可用于数据库函数,并能够动态传参下面经过一些具体的案例来练习条件构造器的使用。(使用前文建立的user
表)
// 案例先展现须要完成的SQL语句,后展现Wrapper的写法 // 1. 名字中包含佳,且年龄小于25 // SELECT * FROM user WHERE name like '%佳%' AND age < 25 QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.like("name", "佳").lt("age", 25); List<User> users = userMapper.selectList(wrapper); // 下面展现SQL时,仅展现WHERE条件;展现代码时, 仅展现Wrapper构建部分 // 2. 姓名为黄姓,且年龄大于等于20,小于等于40,且email字段不为空 // name like '黄%' AND age BETWEEN 20 AND 40 AND email is not null wrapper.likeRight("name","黄").between("age", 20, 40).isNotNull("email"); // 3. 姓名为黄姓,或者年龄大于等于40,按照年龄降序排列,年龄相同则按照id升序排列 // name like '黄%' OR age >= 40 order by age desc, id asc wrapper.likeRight("name","黄").or().ge("age",40).orderByDesc("age").orderByAsc("id"); // 4.建立日期为2021年3月22日,而且直属上级的名字为李姓 // date_format(create_time,'%Y-%m-%d') = '2021-03-22' AND manager_id IN (SELECT id FROM user WHERE name like '李%') wrapper.apply("date_format(create_time, '%Y-%m-%d') = {0}", "2021-03-22") // 建议采用{index}这种方式动态传参, 可防止SQL注入 .inSql("manager_id", "SELECT id FROM user WHERE name like '李%'"); // 上面的apply, 也能够直接使用下面这种方式作字符串拼接,但当这个日期是一个外部参数时,这种方式有SQL注入的风险 wrapper.apply("date_format(create_time, '%Y-%m-%d') = '2021-03-22'"); // 5. 名字为王姓,而且(年龄小于40,或者邮箱不为空) // name like '王%' AND (age < 40 OR email is not null) wrapper.likeRight("name", "王").and(q -> q.lt("age", 40).or().isNotNull("email")); // 6. 名字为王姓,或者(年龄小于40而且年龄大于20而且邮箱不为空) // name like '王%' OR (age < 40 AND age > 20 AND email is not null) wrapper.likeRight("name", "王").or( q -> q.lt("age",40) .gt("age",20) .isNotNull("email") ); // 7. (年龄小于40或者邮箱不为空) 而且名字为王姓 // (age < 40 OR email is not null) AND name like '王%' wrapper.nested(q -> q.lt("age", 40).or().isNotNull("email")) .likeRight("name", "王"); // 8. 年龄为30,31,34,35 // age IN (30,31,34,35) wrapper.in("age", Arrays.asList(30,31,34,35)); // 或 wrapper.inSql("age","30,31,34,35"); // 9. 年龄为30,31,34,35, 返回知足条件的第一条记录 // age IN (30,31,34,35) LIMIT 1 wrapper.in("age", Arrays.asList(30,31,34,35)).last("LIMIT 1"); // 10. 只选出id, name 列 (QueryWrapper 特有) // SELECT id, name FROM user; wrapper.select("id", "name"); // 11. 选出id, name, age, email, 等同于排除 manager_id 和 create_time // 当列特别多, 而只须要排除个别列时, 采用上面的方式可能须要写不少个列, 能够采用重载的select方法,指定须要排除的列 wrapper.select(User.class, info -> { String columnName = info.getColumn(); return !"create_time".equals(columnName) && !"manager_id".equals(columnName); });
条件构造器的诸多方法中,都可以指定一个boolean
类型的参数condition
,用来决定该条件是否加入最后生成的WHERE语句中,好比
String name = "黄"; // 假设name变量是一个外部传入的参数 QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.like(StringUtils.hasText(name), "name", name); // 仅当 StringUtils.hasText(name) 为 true 时, 会拼接这个like语句到WHERE中 // 其实就是对下面代码的简化 if (StringUtils.hasText(name)) { wrapper.like("name", name); }
调用构造函数建立一个Wrapper
对象时,能够传入一个实体对象。后续使用这个Wrapper
时,会以实体对象中的非空属性,构建WHERE条件(默认构建等值匹配的WHERE条件,这个行为能够经过实体类里各个字段上的@TableField
注解中的condition
属性进行改变)
示例以下
@Test public void test3() { User user = new User(); user.setName("黄主管"); user.setAge(28); QueryWrapper<User> wrapper = new QueryWrapper<>(user); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); } 复制代码
执行结果以下。能够看到,是根据实体对象中的非空属性,进行了等值匹配查询。
若但愿针对某些属性,改变等值匹配的行为,则能够在实体类中用@TableField
注解进行配置,示例以下
package com.example.mp.po; import com.baomidou.mybatisplus.annotation.SqlCondition; import com.baomidou.mybatisplus.annotation.TableField; import lombok.Data; import java.time.LocalDateTime; @Data public class User { private Long id; @TableField(condition = SqlCondition.LIKE) // 配置该字段使用like进行拼接 private String name; private Integer age; private String email; private Long managerId; private LocalDateTime createTime; }
运行下面的测试代码
@Test public void test3() { User user = new User(); user.setName("黄"); QueryWrapper<User> wrapper = new QueryWrapper<>(user); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); }
从下图获得的结果来看,对于实体对象中的name
字段,采用了like
进行拼接
@TableField
中配置的condition
属性实则是一个字符串,SqlCondition
类中预约义了一些字符串以供选择
package com.baomidou.mybatisplus.annotation; public class SqlCondition { //下面的字符串中, %s 是占位符, 第一个 %s 是列名, 第二个 %s 是列的值 public static final String EQUAL = "%s=#{%s}"; public static final String NOT_EQUAL = "%s<>#{%s}"; public static final String LIKE = "%s LIKE CONCAT('%%',#{%s},'%%')"; public static final String LIKE_LEFT = "%s LIKE CONCAT('%%',#{%s})"; public static final String LIKE_RIGHT = "%s LIKE CONCAT(#{%s},'%%')"; }
SqlCondition
中提供的配置比较有限,当咱们须要<
或>
等拼接方式,则须要本身定义。好比
package com.example.mp.po; import com.baomidou.mybatisplus.annotation.SqlCondition; import com.baomidou.mybatisplus.annotation.TableField; import lombok.Data; import java.time.LocalDateTime; @Data public class User { private Long id; @TableField(condition = SqlCondition.LIKE) private String name; @TableField(condition = "%s > #{%s}") // 这里至关于大于, 其中 > 是字符实体 private Integer age; private String email; private Long managerId; private LocalDateTime createTime; }
测试以下
@Test public void test3() { User user = new User(); user.setName("黄"); user.setAge(30); QueryWrapper<User> wrapper = new QueryWrapper<>(user); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); }
从下图获得的结果,能够看出,name
属性是用like
拼接的,而age
属性是用>
拼接的
allEq方法传入一个map
,用来作等值匹配
@Test public void test3() { QueryWrapper<User> wrapper = new QueryWrapper<>(); Map<String, Object> param = new HashMap<>(); param.put("age", 40); param.put("name", "黄飞飞"); wrapper.allEq(param); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); }
当allEq方法传入的Map中有value为null
的元素时,默认会设置为is null
@Test public void test3() { QueryWrapper<User> wrapper = new QueryWrapper<>(); Map<String, Object> param = new HashMap<>(); param.put("age", 40); param.put("name", null); wrapper.allEq(param); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); }
若想忽略map中value为null
的元素,能够在调用allEq时,设置参数boolean null2IsNull
为false
@Test public void test3() { QueryWrapper<User> wrapper = new QueryWrapper<>(); Map<String, Object> param = new HashMap<>(); param.put("age", 40); param.put("name", null); wrapper.allEq(param, false); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); }
若想要在执行allEq时,过滤掉Map中的某些元素,能够调用allEq的重载方法allEq(BiPredicate<R, V> filter, Map<R, V> params)
@Test public void test3() { QueryWrapper<User> wrapper = new QueryWrapper<>(); Map<String, Object> param = new HashMap<>(); param.put("age", 40); param.put("name", "黄飞飞"); wrapper.allEq((k,v) -> !"name".equals(k), param); // 过滤掉map中key为name的元素 List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); }
lambda条件构造器,支持lambda表达式,能够没必要像普通条件构造器同样,以字符串形式指定列名,它能够直接以实体类的方法引用来指定列。示例以下
@Test public void testLambda() { LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>(); wrapper.like(User::getName, "黄").lt(User::getAge, 30); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); }
像普通的条件构造器,列名是用字符串的形式指定,没法在编译期进行列名合法性的检查,这就不如lambda条件构造器来的优雅。
另外,还有个链式lambda条件构造器,使用示例以下
@Test public void testLambda() { LambdaQueryChainWrapper<User> chainWrapper = new LambdaQueryChainWrapper<>(userMapper); List<User> users = chainWrapper.like(User::getName, "黄").gt(User::getAge, 30).list(); users.forEach(System.out::println); }
上面介绍的都是查询操做,如今来说更新和删除操做。
BaseMapper
中提供了2个更新方法
updateById(T entity)
根据入参entity
的id
(主键)进行更新,对于entity
中非空的属性,会出如今UPDATE语句的SET后面,即entity
中非空的属性,会被更新到数据库,示例以下
@RunWith(SpringRunner.class) @SpringBootTest public class UpdateTest { @Autowired private UserMapper userMapper; @Test public void testUpdate() { User user = new User(); user.setId(2L); user.setAge(18); userMapper.updateById(user); } }
update(T entity, Wrapper<T> wrapper)
根据实体entity
和条件构造器wrapper
进行更新,示例以下
@Test public void testUpdate2() { User user = new User(); user.setName("王三蛋"); LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>(); wrapper.between(User::getAge, 26,31).likeRight(User::getName,"吴"); userMapper.update(user, wrapper); }
额外演示一下,把实体对象传入Wrapper
,即用实体对象构造WHERE条件的案例
@Test public void testUpdate3() { User whereUser = new User(); whereUser.setAge(40); whereUser.setName("王"); LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>(whereUser); User user = new User(); user.setEmail("share@baomidou.com"); user.setManagerId(10L); userMapper.update(user, wrapper); }
注意到咱们的User类中,对name
属性和age
属性进行了以下的设置
@Data public class User { private Long id; @TableField(condition = SqlCondition.LIKE) private String name; @TableField(condition = "%s > #{%s}") private Integer age; private String email; private Long managerId; private LocalDateTime createTime; }
执行结果
再额外演示一下,链式lambda条件构造器的使用
@Test public void testUpdate5() { LambdaUpdateChainWrapper<User> wrapper = new LambdaUpdateChainWrapper<>(userMapper); wrapper.likeRight(User::getEmail, "share") .like(User::getName, "飞飞") .set(User::getEmail, "ff@baomidou.com") .update(); }
反思
因为BaseMapper
提供的2个更新方法都是传入一个实体对象去执行更新,这在须要更新的列比较多时还好,若想要更新的只有那么一列,或者两列,则建立一个实体对象就显得有点麻烦。针对这种状况,UpdateWrapper
提供有set
方法,能够手动拼接SQL中的SET语句,此时能够没必要传入实体对象,示例以下
@Test public void testUpdate4() { LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>(); wrapper.likeRight(User::getEmail, "share").set(User::getManagerId, 9L); userMapper.update(null, wrapper); }
BaseMapper
一共提供了以下几个用于删除的方法
deleteById
根据主键id进行删除deleteBatchIds
根据主键id进行批量删除deleteByMap
根据Map进行删除(Map中的key为列名,value为值,根据列和值进行等值匹配)delete(Wrapper<T> wrapper)
根据条件构造器Wrapper
进行删除与前面查询和更新的操做大同小异,不作赘述
当mp提供的方法还不能知足需求时,则能够自定义SQL。
示例以下
package com.example.mp.mappers; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.mp.po.User; import org.apache.ibatis.annotations.Select; import java.util.List; /** * @Author yogurtzzz * @Date 2021/3/18 11:21 **/ public interface UserMapper extends BaseMapper<User> { @Select("select * from user") List<User> selectRaw(); }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.mp.mappers.UserMapper"> <select id="selectRaw" resultType="com.example.mp.po.User"> SELECT * FROM user </select> </mapper> package com.example.mp.mappers; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.mp.po.User; import org.apache.ibatis.annotations.Select; import java.util.List; public interface UserMapper extends BaseMapper<User> { List<User> selectRaw(); }
使用xml时,若xml文件与mapper接口文件不在同一目录下,则须要在application.yml
中配置mapper.xml的存放路径
mybatis-plus: mapper-locations: /mappers/*
如有多个地方存放mapper,则用数组形式进行配置
mybatis-plus: mapper-locations: - /mappers/* - /com/example/mp/*
测试代码以下
@Test public void testCustomRawSql() { List<User> users = userMapper.selectRaw(); users.forEach(System.out::println); }
结果
也可使用mp提供的Wrapper条件构造器,来自定义SQL
示例以下
package com.example.mp.mappers; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.toolkit.Constants; import com.example.mp.po.User; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; public interface UserMapper extends BaseMapper<User> { // SQL中不写WHERE关键字,且固定使用${ew.customSqlSegment} @Select("select * from user ${ew.customSqlSegment}") List<User> findAll(@Param(Constants.WRAPPER)Wrapper<User> wrapper); }
package com.example.mp.mappers; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.mp.po.User; import java.util.List; public interface UserMapper extends BaseMapper<User> { List<User> findAll(Wrapper<User> wrapper); } 复制代码 <!-- UserMapper.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.mp.mappers.UserMapper"> <select id="findAll" resultType="com.example.mp.po.User"> SELECT * FROM user ${ew.customSqlSegment} </select> </mapper>
BaseMapper
中提供了2个方法进行分页查询,分别是selectPage
和selectMapsPage
,前者会将查询的结果封装成Java实体对象,后者会封装成Map<String,Object>
。分页查询的食用示例以下
package com.example.mp.config; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MybatisPlusConfig { /** 新版mp **/ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } /** 旧版mp 用 PaginationInterceptor **/ }
@Test public void testPage() { LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>(); wrapper.ge(User::getAge, 28); // 设置分页信息, 查第3页, 每页2条数据 Page<User> page = new Page<>(3, 2); // 执行分页查询 Page<User> userPage = userMapper.selectPage(page, wrapper); System.out.println("总记录数 = " + userPage.getTotal()); System.out.println("总页数 = " + userPage.getPages()); System.out.println("当前页码 = " + userPage.getCurrent()); // 获取分页查询结果 List<User> records = userPage.getRecords(); records.forEach(System.out::println); }
结果
其余
Page
的重载构造函数,指定isSearchCount
为false
便可public Page(long current, long size, boolean isSearchCount)
在实际开发中,可能遇到多表联查的场景,此时BaseMapper
中提供的单表分页查询的方法没法知足需求,须要自定义SQL,示例以下(使用单表查询的SQL进行演示,实际进行多表联查时,修改SQL语句便可)
// 这里采用纯注解方式。固然,若SQL比较复杂,建议仍是采用XML的方式 @Select("SELECT * FROM user ${ew.customSqlSegment}") Page<User> selectUserPage(Page<User> page, @Param(Constants.WRAPPER) Wrapper<User> wrapper);
2. 执行查询
@Test public void testPage2() { LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>(); wrapper.ge(User::getAge, 28).likeRight(User::getName, "王"); Page<User> page = new Page<>(3,2); Page<User> userPage = userMapper.selectUserPage(page, wrapper); System.out.println("总记录数 = " + userPage.getTotal()); System.out.println("总页数 = " + userPage.getPages()); userPage.getRecords().forEach(System.out::println); }
ActiveRecord模式,经过操做实体对象,直接操做数据库表。与ORM有点相似。
示例以下
User
继承自Model
package com.example.mp.po; import com.baomidou.mybatisplus.annotation.SqlCondition; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.extension.activerecord.Model; import lombok.Data; import lombok.EqualsAndHashCode; import java.time.LocalDateTime; @EqualsAndHashCode(callSuper = false) @Data public class User extends Model<User> { private Long id; @TableField(condition = SqlCondition.LIKE) private String name; @TableField(condition = "%s > #{%s}") private Integer age; private String email; private Long managerId; private LocalDateTime createTime; }
@Test public void insertAr() { User user = new User(); user.setId(15L); user.setName("我是AR猪"); user.setAge(1); user.setEmail("ar@baomidou.com"); user.setManagerId(1L); boolean success = user.insert(); // 插入 System.out.println(success); }
其余示例
// 查询 @Test public void selectAr() { User user = new User(); user.setId(15L); User result = user.selectById(); System.out.println(result); } // 更新 @Test public void updateAr() { User user = new User(); user.setId(15L); user.setName("王全蛋"); user.updateById(); } //删除 @Test public void deleteAr() { User user = new User(); user.setId(15L); user.deleteById(); }
在定义实体类时,用@TableId
指定主键,而其type
属性,能够指定主键策略。
mp支持多种主键策略,默认的策略是基于雪花算法的自增id。所有主键策略定义在了枚举类IdType
中,IdType
有以下的取值
AUTO
数据库ID自增,依赖于数据库。在插入操做生成SQL语句时,不会插入主键这一列
NONE
未设置主键类型。若在代码中没有手动设置主键,则会根据主键的全局策略自动生成(默认的主键全局策略是基于雪花算法的自增ID)
INPUT
须要手动设置主键,若不设置。插入操做生成SQL语句时,主键这一列的值会是null
。oracle的序列主键须要使用这种方式
ASSIGN_ID
当没有手动设置主键,即实体类中的主键属性为空时,才会自动填充,使用雪花算法
ASSIGN_UUID
当实体类的主键属性为空时,才会自动填充,使用UUID
能够针对每一个实体类,使用@TableId
注解指定该实体类的主键策略,这能够理解为局部策略。若但愿对全部的实体类,都采用同一种主键策略,挨个在每一个实体类上进行配置,则太麻烦了,此时能够用主键的全局策略。只须要在application.yml
进行配置便可。好比,配置了全局采用自增主键策略
# application.yml mybatis-plus: global-config: db-config: id-type: auto
下面对不一样主键策略的行为进行演示
AUTO
在User
上对id
属性加上注解,而后将MYSQL的user
表修改其主键为自增。
@EqualsAndHashCode(callSuper = false) @Data public class User extends Model<User> { @TableId(type = IdType.AUTO) private Long id; @TableField(condition = SqlCondition.LIKE) private String name; @TableField(condition = "%s > #{%s}") private Integer age; private String email; private Long managerId; private LocalDateTime createTime; }
测试
@Test public void testAuto() { User user = new User(); user.setName("我是青蛙呱呱"); user.setAge(99); user.setEmail("frog@baomidou.com"); user.setCreateTime(LocalDateTime.now()); userMapper.insert(user); System.out.println(user.getId()); }
结果
能够看到,代码中没有设置主键ID,发出的SQL语句中也没有设置主键ID,而且插入结束后,主键ID会被写回到实体对象。
NONE
在MYSQL的user
表中,去掉主键自增。而后修改User
类(若不配置@TableId
注解,默认主键策略也是NONE
)
@TableId(type = IdType.NONE) private Long id;
插入时,若实体类的主键ID有值,则使用之;若主键ID为空,则使用主键全局策略,来生成一个ID。
小结
AUTO
依赖于数据库的自增主键,插入时,实体对象无需设置主键,插入成功后,主键会被写回实体对象。
INPUT`彻底依赖于用户输入。实体对象中主键ID是什么,插入到数据库时就设置什么。如有值便设置值,若为`null`则设置`null
其他的几个策略,都是在实体对象中主键ID为空时,才会自动生成。
NONE
会跟随全局策略,ASSIGN_ID
采用雪花算法,ASSIGN_UUID
采用UUID
全局配置,在application.yml
中进行便可;针对单个实体类的局部配置,使用@TableId
便可。对于某个实体类,若它有局部主键策略,则采用之,不然,跟随全局策略。
mybatis plus有许多可配置项,可在application.yml
中进行配置,如上面的全局主键策略。下面列举部分配置项
configLocation
:如有单独的mybatis配置,用这个注解指定mybatis的配置文件(mybatis的全局配置文件)mapperLocations
:mybatis mapper所对应的xml文件的位置typeAliasesPackage
:mybatis的别名包扫描路径mapUnderscoreToCamelCase
:是否开启自动驼峰命名规则映射。(默认开启)dbTpe
:数据库类型。通常不用配,会根据数据库链接url自动识别fieldStrategy
:(已过期)字段验证策略。该配置项在最新版的mp文档中已经找不到了,被细分红了insertStrategy
,updateStrategy
,selectStrategy
。默认值是NOT_NULL
,即对于实体对象中非空的字段,才会组装到最终的SQL语句中。
有以下几种可选配置
IGNORED
:忽略校验。即,不作校验。实体对象中的所有字段,不管值是什么,都如实地被组装到SQL语句中(为NULL
的字段在SQL语句中就组装为NULL
)。NOT_NULL
:非NULL
校验。只会将非NULL
的字段组装到SQL语句中NOT_EMPTY
:非空校验。当有字段是字符串类型时,只组装非空字符串;对其余类型的字段,等同于NOT_NULL
NEVER
:不加入SQL。全部字段不加入到SQL语句这个配置项,可在application.yml
中进行全局配置,也能够在某一实体类中,对某一字段用@TableField
注解进行局部配置
这个字段验证策略有什么用呢?在UPDATE操做中可以体现出来,若用一个User
对象执行UPDATE操做,咱们但愿只对User
对象中非空的属性,更新到数据库中,其余属性不作更新,则NOT_NULL
能够知足需求。而若updateStrategy
配置为IGNORED
,则不会进行非空判断,会将实体对象中的所有属性如实组装到SQL中,这样,执行UPDATE时,可能就将一些不想更新的字段,设置为了NULL
。
tablePrefix
:添加表名前缀
好比
mybatis-plus: global-config: db-config: table-prefix: xx_
而后将MYSQL中的表作一下修改。但Java实体类保持不变(仍然为User
)。
测试
@Test public void test3() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.like("name", "黄"); Integer count = userMapper.selectCount(wrapper); System.out.println(count); }
能够看到拼接出来的SQL,在表名前面添加了前缀
mp提供一个生成器,可快速生成Entity实体类,Mapper接口,Service,Controller等全套代码。
示例以下
public class GeneratorTest { @Test public void generate() { AutoGenerator generator = new AutoGenerator(); // 全局配置 GlobalConfig config = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); // 设置输出到的目录 config.setOutputDir(projectPath + "/src/main/java"); config.setAuthor("yogurt"); // 生成结束后是否打开文件夹 config.setOpen(false); // 全局配置添加到 generator 上 generator.setGlobalConfig(config); // 数据源配置 DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/yogurt?serverTimezone=Asia/Shanghai"); dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver"); dataSourceConfig.setUsername("root"); dataSourceConfig.setPassword("root"); // 数据源配置添加到 generator generator.setDataSource(dataSourceConfig); // 包配置, 生成的代码放在哪一个包下 PackageConfig packageConfig = new PackageConfig(); packageConfig.setParent("com.example.mp.generator"); // 包配置添加到 generator generator.setPackageInfo(packageConfig); // 策略配置 StrategyConfig strategyConfig = new StrategyConfig(); // 下划线驼峰命名转换 strategyConfig.setNaming(NamingStrategy.underline_to_camel); strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel); // 开启lombok strategyConfig.setEntityLombokModel(true); // 开启RestController strategyConfig.setRestControllerStyle(true); generator.setStrategy(strategyConfig); generator.setTemplateEngine(new FreemarkerTemplateEngine()); // 开始生成 generator.execute(); } }
运行后,能够看到生成了以下图所示的全套代码
高级功能的演示须要用到一张新的表user2
DROP TABLE IF EXISTS user2; CREATE TABLE user2 ( id BIGINT(20) PRIMARY KEY NOT NULL COMMENT '主键id', name VARCHAR(30) DEFAULT NULL COMMENT '姓名', age INT(11) DEFAULT NULL COMMENT '年龄', email VARCHAR(50) DEFAULT NULL COMMENT '邮箱', manager_id BIGINT(20) DEFAULT NULL COMMENT '直属上级id', create_time DATETIME DEFAULT NULL COMMENT '建立时间', update_time DATETIME DEFAULT NULL COMMENT '修改时间', version INT(11) DEFAULT '1' COMMENT '版本', deleted INT(1) DEFAULT '0' COMMENT '逻辑删除标识,0-未删除,1-已删除', CONSTRAINT manager_fk FOREIGN KEY(manager_id) REFERENCES user2(id) ) ENGINE = INNODB CHARSET=UTF8; INSERT INTO user2(id, name, age, email, manager_id, create_time) VALUES (1, '老板', 40 ,'boss@baomidou.com' ,NULL, '2021-03-28 13:12:40'), (2, '王狗蛋', 40 ,'gd@baomidou.com' ,1, '2021-03-28 13:12:40'), (3, '王鸡蛋', 40 ,'jd@baomidou.com' ,2, '2021-03-28 13:12:40'), (4, '王鸭蛋', 40 ,'yd@baomidou.com' ,2, '2021-03-28 13:12:40'), (5, '王猪蛋', 40 ,'zd@baomidou.com' ,2, '2021-03-28 13:12:40'), (6, '王软蛋', 40 ,'rd@baomidou.com' ,2, '2021-03-28 13:12:40'), (7, '王铁蛋', 40 ,'td@baomidou.com' ,2, '2021-03-28 13:12:40') 复制代码
并建立对应的实体类User2
package com.example.mp.po; import lombok.Data; import java.time.LocalDateTime; @Data public class User2 { private Long id; private String name; private Integer age; private String email; private Long managerId; private LocalDateTime createTime; private LocalDateTime updateTime; private Integer version; private Integer deleted; }
以及Mapper接口
package com.example.mp.mappers; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.mp.po.User2; public interface User2Mapper extends BaseMapper<User2> { }
首先,为何要有逻辑删除呢?直接删掉不行吗?固然能够,但往后若想要恢复,或者须要查看这些数据,就作不到了。逻辑删除是为了方便数据恢复,和保护数据自己价值的一种方案。
平常中,咱们在电脑中删除一个文件后,也仅仅是把该文件放入了回收站,往后如有须要还能进行查看或恢复。当咱们肯定再也不须要某个文件,能够将其从回收站中完全删除。这也是相似的道理。
mp提供的逻辑删除实现起来很是简单
只须要在application.yml
中进行逻辑删除的相关配置便可
mybatis-plus: global-config: db-config: logic-delete-field: deleted # 全局逻辑删除的实体字段名 logic-delete-value: 1 # 逻辑已删除值(默认为1) logic-not-delete-value: 0 # 逻辑未删除值(默认为0) # 若逻辑已删除和未删除的值和默认值同样,则能够不配置这2项
测试代码
package com.example.mp; import com.example.mp.mappers.User2Mapper; import com.example.mp.po.User2; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class LogicDeleteTest { @Autowired private User2Mapper mapper; @Test public void testLogicDel() { int i = mapper.deleteById(6); System.out.println("rowAffected = " + i); } }
结果
能够看到,发出的SQL再也不是DELETE
,而是UPDATE
此时咱们再执行一次SELECT
@Test public void testSelect() { List<User2> users = mapper.selectList(null); }
能够看到,发出的SQL语句,会自动在WHERE后面拼接逻辑未删除的条件。查询出来的结果中,没有了id为6的王软蛋。
若想要SELECT的列,不包括逻辑删除的那一列,则能够在实体类中经过@TableField
进行配置
@TableField(select = false) private Integer deleted; 复制代码
能够看到下图的执行结果中,SELECT中已经不包含deleted这一列了
前面在application.yml
中作的配置,是全局的。一般来讲,对于多个表,咱们也会统一逻辑删除字段的名称,统一逻辑已删除和未删除的值,因此全局配置便可。固然,若要对某些表进行单独配置,在实体类的对应字段上使用@TableLogic
便可
@TableLogic(value = "0", delval = "1") private Integer deleted;
小结
开启mp的逻辑删除后,会对SQL产生以下的影响
注意,上述的影响,只针对mp自动注入的SQL生效。若是是本身手动添加的自定义SQL,则不会生效。好比
public interface User2Mapper extends BaseMapper<User2> { @Select("select * from user2") List<User2> selectRaw(); }
调用这个selectRaw
,则mp的逻辑删除不会生效。
另,逻辑删除可在application.yml
中进行全局配置,也可在实体类中用@TableLogic
进行局部配置。
表中经常会有“新增时间”,“修改时间”,“操做人” 等字段。比较原始的方式,是每次插入或更新时,手动进行设置。mp能够经过配置,对某些字段进行自动填充,食用示例以下
@TableField
设置自动填充public class User2 { private Long id; private String name; private Integer age; private String email; private Long managerId; @TableField(fill = FieldFill.INSERT) // 插入时自动填充 private LocalDateTime createTime; @TableField(fill = FieldFill.UPDATE) // 更新时自动填充 private LocalDateTime updateTime; private Integer version; private Integer deleted; }
package com.example.mp.component; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; import java.time.LocalDateTime; @Component //须要注册到Spring容器中 public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { // 插入时自动填充 // 注意第二个参数要填写实体类中的字段名称,而不是表的列名称 strictFillStrategy(metaObject, "createTime", LocalDateTime::now); } @Override public void updateFill(MetaObject metaObject) { // 更新时自动填充 strictFillStrategy(metaObject, "updateTime", LocalDateTime::now); } }
测试
@Test public void test() { User2 user = new User2(); user.setId(8L); user.setName("王一蛋"); user.setAge(29); user.setEmail("yd@baomidou.com"); user.setManagerId(2L); mapper.insert(user); }
根据下图结果,能够看到对createTime进行了自动填充
注意,自动填充仅在该字段为空时会生效,若该字段不为空,则直接使用已有的值。以下
@Test public void test() { User2 user = new User2(); user.setId(8L); user.setName("王一蛋"); user.setAge(29); user.setEmail("yd@baomidou.com"); user.setManagerId(2L); user.setCreateTime(LocalDateTime.of(2000,1,1,8,0,0)); mapper.insert(user); }
更新时的自动填充,测试以下
@Test public void test() { User2 user = new User2(); user.setId(8L); user.setName("王一蛋"); user.setAge(99); mapper.updateById(user); }
当出现并发操做时,须要确保各个用户对数据的操做不产生冲突,此时须要一种并发控制手段。悲观锁的方法是,在对数据库的一条记录进行修改时,先直接加锁(数据库的锁机制),锁定这条数据,而后再进行操做;而乐观锁,正如其名,它先假设不存在冲突状况,而在实际进行数据操做时,再检查是否冲突。乐观锁的一种一般实现是版本号,在MySQL中也有名为MVCC的基于版本号的并发事务控制。
在读多写少的场景下,乐观锁比较适用,可以减小加锁操做致使的性能开销,提升系统吞吐量。
在写多读少的场景下,悲观锁比较使用,不然会由于乐观锁不断失败重试,反而致使性能降低。
乐观锁的实现以下:
这种思想和CAS(Compare And Swap)很是类似。
乐观锁的实现步骤以下
package com.example.mp.config; import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MybatisPlusConfig { /** 3.4.0之后的mp版本,推荐用以下的配置方式 **/ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return interceptor; } /** 旧版mp能够采用以下方式。注意新旧版本中,新版的类,名称带有Inner, 旧版的不带, 不要配错了 **/ /* @Bean public OptimisticLockerInterceptor opLocker() { return new OptimisticLockerInterceptor(); } */ }
@Version
@Data public class User2 { private Long id; private String name; private Integer age; private String email; private Long managerId; private LocalDateTime createTime; private LocalDateTime updateTime; @Version private Integer version; private Integer deleted; }
测试代码
@Test public void testOpLocker() { int version = 1; // 假设这个version是先前查询时得到的 User2 user = new User2(); user.setId(8L); user.setEmail("version@baomidou.com"); user.setVersion(version); int i = mapper.updateById(user); }
执行以前先看一下数据库的状况
根据下图执行结果,能够看到SQL语句中添加了version相关的操做
当UPDATE返回了1,表示影响行数为1,则更新成功。反之,因为WHERE后面的version与数据库中的不一致,匹配不到任何记录,则影响行数为0,表示更新失败。更新成功后,新的version会被封装回实体对象中。
实体类中version字段,类型只支持int,long,Date,Timestamp,LocalDateTime
注意,乐观锁插件仅支持updateById(id)
与update(entity, wrapper)
方法
注意:若是使用wrapper
,则wrapper
不能复用!示例以下
@Test public void testOpLocker() { User2 user = new User2(); user.setId(8L); user.setVersion(1); user.setAge(2); // 第一次使用 LambdaQueryWrapper<User2> wrapper = new LambdaQueryWrapper<>(); wrapper.eq(User2::getName, "王一蛋"); mapper.update(user, wrapper); // 第二次复用 user.setAge(3); mapper.update(user, wrapper); }
能够看到在第二次复用wrapper
时,拼接出的SQL中,后面WHERE语句中出现了2次version,是有问题的。
该插件会输出SQL语句的执行时间,以便作SQL语句的性能分析和调优。
注:3.2.0版本以后,mp自带的性能分析插件被官方移除了,而推荐食用第三方性能分析插件
食用步骤
<dependency> <groupId>p6spy</groupId> <artifactId>p6spy</artifactId> <version>3.9.1</version> </dependency>
application.yml
spring: datasource: driver-class-name: com.p6spy.engine.spy.P6SpyDriver #换成p6spy的驱动 url: jdbc:p6spy:mysql://localhost:3306/yogurt?serverTimezone=Asia/Shanghai #url修改 username: root password: root
src/main/resources
资源目录下添加spy.properties
#spy.properties #3.2.1以上使用 modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory # 真实JDBC driver , 多个以逗号分割,默认为空。因为上面设置了modulelist, 这里能够不用设置driverlist #driverlist=com.mysql.cj.jdbc.Driver # 自定义日志打印 logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger #日志输出到控制台 appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger #若要日志输出到文件, 把上面的appnder注释掉, 或者采用下面的appender, 再添加logfile配置 #不配置appender时, 默认是往文件进行输出的 #appender=com.p6spy.engine.spy.appender.FileLogger #logfile=log.log # 设置 p6spy driver 代理 deregisterdrivers=true # 取消JDBC URL前缀 useprefix=true # 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset. excludecategories=info,debug,result,commit,resultset # 日期格式 dateformat=yyyy-MM-dd HH:mm:ss # 是否开启慢SQL记录 outagedetection=true # 慢SQL记录标准 2 秒 outagedetectioninterval=2 # 执行时间设置, 只有超过这个执行时间的才进行记录, 默认值0, 单位毫秒 executionThreshold=10
随便运行一个测试用例,能够看到该SQL的执行时长被记录了下来
多租户的概念:多个用户共用一套系统,但他们的数据有须要相对的独立,保持必定的隔离性。
多租户的数据隔离通常有以下的方式:
不一样租户使用不一样的数据库服务器
优势是:不一样租户有不一样的独立数据库,有助于扩展,以及对不一样租户提供更好的个性化,出现故障时恢复数据较为简单。
缺点是:增长了数据库数量,购置成本,维护成本更高
不一样租户使用相同的数据库服务器,但使用不一样的数据库(不一样的schema)
优势是购置和维护成本低了一些,缺点是数据恢复较为困难,由于不一样租户的数据都放在了一块儿
不一样租户使用相同的数据库服务器,使用相同的数据库,共享数据表,在表中增长租户id来作区分
优势是,购置和维护成本最低,支持用户最多,缺点是隔离性最低,安全性最低
食用实例以下
添加多租户拦截器配置。添加配置后,在执行CRUD的时候,会自动在SQL语句最后拼接租户id的条件
package com.example.mp.config; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler; import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.LongValue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() { @Override public Expression getTenantId() { // 返回租户id的值, 这里固定写死为1 // 通常是从当前上下文中取出一个 租户id return new LongValue(1); } /** ** 一般会将表示租户id的列名,须要排除租户id的表等信息,封装到一个配置类中(如TenantConfig) **/ @Override public String getTenantIdColumn() { // 返回表中的表示租户id的列名 return "manager_id"; } @Override public boolean ignoreTable(String tableName) { // 表名不为 user2 的表, 不拼接多租户条件 return !"user2".equals(tableName); } })); // 若是用了分页插件注意先 add TenantLineInnerInterceptor 再 add PaginationInnerInterceptor // 用了分页插件必须设置 MybatisConfiguration#useDeprecatedExecutor = false return interceptor; } }
测试代码
@Test public void testTenant() { LambdaQueryWrapper<User2> wrapper = new LambdaQueryWrapper<>(); wrapper.likeRight(User2::getName, "王") .select(User2::getName, User2::getAge, User2::getEmail, User2::getManagerId); user2Mapper.selectList(wrapper); }
当数据量特别大的时候,咱们一般会采用分库分表。这时,可能就会有多张表,其表结构相同,但表名不一样。例如order_1
,order_2
,order_3
,查询时,咱们可能须要动态设置要查的表名。mp提供了动态表名SQL解析器,食用示例以下
先在mysql中拷贝一下user2
表
配置动态表名拦截器
package com.example.mp.config; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler; import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashMap; import java.util.Random; @Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor(); HashMap<String, TableNameHandler> map = new HashMap<>(); // 对于user2表,进行动态表名设置 map.put("user2", (sql, tableName) -> { String _ = "_"; int random = new Random().nextInt(2) + 1; return tableName + _ + random; // 若返回null, 则不会进行动态表名替换, 仍是会使用user2 }); dynamicTableNameInnerInterceptor.setTableNameHandlerMap(map); interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor); return interceptor; } }
测试
@Test public void testDynamicTable() { user2Mapper.selectList(null); }
AbstractWrapper
中提供了多个方法用于构造SQL语句中的WHERE条件,而其子类QueryWrapper
额外提供了select
方法,能够只选取特定的列,子类UpdateWrapper
额外提供了set
方法,用于设置SQL中的SET语句。除了普通的Wrapper
,还有基于lambda表达式的Wrapper
,如LambdaQueryWrapper
,LambdaUpdateWrapper
,它们在构造WHERE条件时,直接以方法引用来指定WHERE条件中的列,比普通Wrapper
经过字符串来指定要更加优雅。另,还有链式Wrapper,如LambdaQueryChainWrapper
,它封装了BaseMapper
,能够更方便地获取结果。AND
链接当AND
或OR
后面的条件须要被括号包裹时,将括号中的条件以lambda表达式形式,做为参数传入and()
或or()
特别的,当()
须要放在WHERE语句的最开头时,可使用nested()
方法
apply()
方法进行SQL拼接boolean
类型的变量condition
,来根据须要灵活拼接WHERE条件(仅当condition
为true
时会拼接SQL语句)BaseMapper
提供的selectPage
或selectMapsPage
方法。复杂场景下(如多表联查),使用自定义SQL。Model
便可做者:yogurtzzz
连接: https://juejin.cn/post/696172...