基于SpringBoot和Vue的前后端分离项目
day01 Mybatis Plus入门
一、简介
官网:http://mp.baomidou.com/
参考教程:http://mp.baomidou.com/guide/
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
二、入门
看官方文档可以进行学习,此处只写需要注意的几点。
一 、引入依赖
<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>
<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.3.1</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--lombok用来简化实体类-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--sql 分析打印-->
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.8.2</version>
</dependency>
</dependencies>
之所以不写版本号是因为添加“parent”标签里的内容后,“spring-boot-starter-parent”会为开发者提供常用jar的版本管理,所以我们不需要指定版本,使用人家提供好的就可以了。当然,指定也是可以的,这会覆盖官方默认的版本,不推荐。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
关于mp的版本,3.0.5的版本里许多功能已经不需要加入bean了,默认配置好的,按照我使用的经验来看,好像3.2.0以上的不需要配置“乐观锁”和“分页插件”。
二、配置
在 application.properties 配置文件中添加 MySQL 数据库的相关配置:
spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8
spring.datasource.username=user
spring.datasource.password=123456
spring.profiles.active=dev
#mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
注意:
1、这里的 url 使用了 ?serverTimezone=GMT%2B8 后缀,因为Spring Boot 2.1 集成了 8.0版本的jdbc驱动,这个版本的 jdbc 驱动需要添加这个后缀,否则运行测试用例报告如下错误:
java.sql.SQLException: The server time zone value ‘Öйú±ê׼ʱ¼ä’ is unrecognized or represents more
2、这里的 driver-class-name 使用了 com.mysql.cj.jdbc.Driver ,在 jdbc 8 中 建议使用这个驱动,之前的 com.mysql.jdbc.Driver 已经被废弃,否则运行测试用例的时候会有 WARN 信息
三、部分代码注意点
- 主类
在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹
注意:扫描的包名根据实际情况修改,
且可以写在配置类,如MpConfig中:
@Configuration
@MapperScan("com.yhg.mpdemo.mapper")
public class Mpconfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
- 实体
@Data
public class User {
@TableId(type = IdType.ID_WORKER)
private Long id;
private String name;
private Integer age;
private String email;
//表中含下划线改为驼峰式命名
}
- 测试类的部分示例
@SpringBootTest
public class MpdemoApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void findAll() {
List<User> users = userMapper.selectList(null);
System.out.println(users);
}
//添加操作
@Test
public void addUser() {
User user = new User();
user.setName("hhhhhh2");
user.setAge(70);
user.setEmail("lucy@qq.com");
int insert = userMapper.insert(user);
System.out.println("insert:" + insert);
}
//修改操作
@Test
public void updateUser(){
User user = new User();
user.setId(3L);
user.setAge(120);
int row = userMapper.updateById(user);
System.out.println(row);
}
@Test
public void testLocker(){
//查询
User user = userMapper.selectById(1248623851416322049L);
//修改数据
user.setName("Helen Yao");
user.setEmail("helen@qq.com");
//执行更新
userMapper.updateById(user);
}
@Test
public void testSelect(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1L, 2L, 3L));
System.out.println(users);
}
@Test
public void testPage(){//pagehandler类似
//创建page对象
//传入两个参数,第一个对象是当前页,第二个是每页显示的记录数
Page<User> page = new Page<>(1,3);
//调用mp分页查询的方法
//调用mp分页查询过程中,底层数据封装到page对象里面
userMapper.selectPage(page,null);
//通过page对象获取分页数据
page.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());
}
//删除
@Test
public void testDeleteById(){
int result = userMapper.deleteById(1248818588345819137L);
System.out.println(result);
}
@Test
public void testSelectQuery(){
//创建querywrapper对象
QueryWrapper<User> wrapper = new QueryWrapper<>();
//通过QW设置条件
}
4.注意事项:
- ID_WORKER
MyBatis-Plus默认的主键策略是:ID_WORKER 全局唯一ID - 自增策略
要想主键自增需要配置如下主键策略
需要在创建数据表的时候设置主键自增
实体字段中配置 @TableId(type = IdType.AUTO)
要想影响所有实体的配置,可以设置全局主键配置
#全局设置主键生成策略
mybatis-plus.global-config.db-config.id-type=auto
自动填充
项目中经常会遇到一些数据,每次都使用相同的方式填充,例如记录的创建时间,更新时间等。
我们可以使用MyBatis Plus的自动填充功能,完成这些字段的赋值工作:
(1)数据库表中添加自动填充字段
在User表中添加datetime类型的新的字段 create_time、update_time
(2)实体上添加注解
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
(3)实现元对象处理器接口
注意:不要忘记添加 @Component 注解
Component表示交给spring来处理,Service或者ResponseXXX
//Component表示交给spring来处理,Service或者ResponseXXX
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
乐观锁
主要适用场景:当要更新一条记录的时候,希望这条记录没有被别人更新,也就是说实现线程安全的数据更新
乐观锁实现方式:
取出记录时,获取当前version
更新时,带上这个version
执行更新时, set version = newVersion where version = oldVersion
如果version不对,就更新失败
(1)数据库中添加version字段
ALTER TABLE `user` ADD COLUMN `version` INT
(2)实体类添加version字段
并添加 @Version 注解
@Version
@TableField(fill = FieldFill.INSERT)
private Integer version;//版本号属性
(3)元对象处理器接口添加version的insert默认值
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime",new Date(),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
(3.6以上版本不用了,)
//乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
分页
MyBatis Plus自带分页插件,只要简单的配置即可实现分页功能
(1)创建配置类
此时可以删除主类中的 @MapperScan 扫描注解(新版应该也不用了)
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
逻辑删除
逻辑删除
物理删除:真实删除,将对应数据从数据库中删除,之后查询不到此条被删除数据
逻辑删除:假删除,将对应数据中代表是否被删除字段状态修改为“被删除状态”,之后在数据库中仍旧能看到此条数据记录
(1)数据库中添加 deleted字段
(2)实体类添加deleted 字段
并加上 @TableLogic 注解 和 @TableField(fill = FieldFill.INSERT) 注解
@TableLogic
@TableLogic
@TableField(fill = FieldFill.INSERT)
private Integer deleted;
(3)元对象处理器接口添加deleted的insert默认值
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime",new Date(),metaObject);
}
(4)application.properties 加入配置
此为默认值,如果你的默认值和mp默认的一样,该配置可无
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,才能被选取出来执行逻辑删除的操作
mp的条件构造器wapper
上图表格为条件构造器使用中的各个方法格式和说明,如有不懂可参考官方文档
以下代码转载自:https://blog.csdn.net/m0_37034294/article/details/82917234
构造器条件
package com.lqf.crud;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lqf.crud.bean.crm.User;
import com.lqf.crud.dao.crm.UserMapper;
import com.sun.org.apache.xerces.internal.util.EntityResolverWrapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;
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 org.springframework.web.jsf.el.WebApplicationContextFacesELResolver;
import javax.naming.Name;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class QueryWrapperTests {
@Autowired
private UserMapper mapper;
/**
* <p>
* 根据根据 entity 条件,删除记录,QueryWrapper实体对象封装操作类(可以为 null)
* 下方获取到queryWrapper后删除的查询条件为name字段为null的and年龄大于等于12的and email字段不为null的
* 同理写法条件添加的方式就不做过多介绍了。
* </p>
*/
@Test
public void delete() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper
.isNull("name")
.ge("age", 12)
.isNotNull("email");
int delete = mapper.delete(queryWrapper);
System.out.println("delete return count = " + delete);
}
/**
* <p>
* 根据 entity 条件,查询一条记录,
* 这里和上方删除构造条件一样,只是seletOne返回的是一条实体记录,当出现多条时会报错
* </p>
*/
@Test
public void selectOne() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", "lqf");
User user = mapper.selectOne(queryWrapper);
System.out.println(user);
}
/**
* <p>
* 根据 Wrapper 条件,查询总记录数
* </p>
*
* @param queryWrapper 实体对象
*/
@Test
public void selectCount() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", "lqf");
Integer count = mapper.selectCount(queryWrapper);
System.out.println(count);
}
/**
* <p>
* 根据 entity 条件,查询全部记录
* </p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)为null查询全部
*/
@Test
public void selectList() {
List<User> list = mapper.selectList(null);
System.out.println(list);
}
/**
* <p>
* 根据 Wrapper 条件,查询全部记录
* </p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
@Test
public void selectMaps() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.isNotNull("name");
List<Map<String, Object>> maps = mapper.selectMaps(queryWrapper);
for (Map<String, Object> map : maps) {
System.out.println(map);
}
}
/**
* 打印结果
* {name=lqf, id=1046282328366391406, age=12, email=lqf@163.com, status=false}
* {name=lqf, id=1046282328366391407, age=12, email=lqf@163.com, status=false}
* {name=lqf, id=1046282328366391408, age=12, email=lqf@163.com, status=false}
* {name=lqf, id=1046282328366391409, age=12, email=lqf@163.com, status=false}
* {name=lqf, id=1046282328366391410, age=12, email=lqf@163.com, status=false}
* {name=lqf, id=1046282328366391411, age=12, email=lqf@163.com, status=false}
* {name=lqf, id=1046282328366391412, age=12, email=lqf@163.com, status=false}
* {name=lqf, id=1046282328366391413, age=12, email=lqf@163.com, status=false}
* {name=lqf, id=1046282328366391414, age=12, email=lqf@163.com, status=false}
* {name=lqf, id=1046282328366391415, age=12, email=lqf@163.com, status=false}
* {name=lqf, id=1046282328366391416, age=12, email=lqf@163.com, status=false}
* {name=lqf, id=1046282328366391417, age=12, email=lqf@163.com, status=false}
* {name=lqf, id=1046282328366391418, age=12, email=lqf@163.com, status=false}
* json类型的键值对模式
*/
/**
* <p>
* 根据 entity 条件,查询全部记录(并翻页)
* </p>
*
* @param page 分页查询条件(可以为 RowBounds.DEFAULT)
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
@Test
public void selectPage() {
Page<User> page = new Page<>(1, 5);
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
IPage<User> userIPage = mapper.selectPage(page, queryWrapper);
System.out.println(userIPage);
}
/**
* 打印结果
* ==> Preparing: SELECT COUNT(1) FROM user
* ==> Parameters:
* <== Columns: COUNT(1)
* <== Row: 100
* ==> Preparing: SELECT id,name,age,email,status FROM user LIMIT 0,5
* ==> Parameters:
* <== Columns: id, name, age, email, status
* <== Row: 1046282328366391319, lqf, 12, lqf@163.com, 0
* <== Row: 1046282328366391320, lqf, 12, lqf@163.com, 0
* <== Row: 1046282328366391321, lqf, 12, lqf@163.com, 0
* <== Row: 1046282328366391322, lqf, 12, lqf@163.com, 0
* <== Row: 1046282328366391323, lqf, 12, lqf@163.com, 0
* <== Total: 5
*
*
* 这里需要在项目中加入分页插件
* @Bean
* public PaginationInterceptor paginationInterceptor() {
* return new PaginationInterceptor();
* }
*/
/**
* <p>
* 根据 Wrapper 条件,查询全部记录(并翻页)
* </p>
*
* @param page 分页查询条件
* @param queryWrapper 实体对象封装操作类
*/
@Test
public void selectMapsPage() {
Page<User> page = new Page<>(1, 5);
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
IPage<Map<String, Object>> mapIPage = mapper.selectMapsPage(page, queryWrapper);
System.out.println(mapIPage);
}
/**
* 和上个分页同理只是返回类型不同
*/
/**
* <p>
* 根据 whereEntity 条件,更新记录
* </p>
*
* @param entity 实体对象 (set 条件值,不能为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
@Test
public void update() {
//修改值
User user = new User();
user.setStatus(true);
user.setName("zhangsan");
//修改条件s
UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
userUpdateWrapper.eq("name", "lqf");
int update = mapper.update(user, userUpdateWrapper);
System.out.println(update);
}
/**
* 打印结果
* ==> Preparing: UPDATE user SET name=?, status=? WHERE name = ?
* ==> Parameters: zhangsan(String), true(Boolean), lqf(String)
* <== Updates: 100
* Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@56a4f272]
* 100
* 2018-10-02 15:08:03.928 INFO 7972 --- [ Thread-2] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext@37313c65: startup date [Tue Oct 02 15:08:00 CST 2018]; root of context hierarchy
* 2018-10-02 15:08:03.937 INFO 7972 --- [ Thread-2] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
* 2018-10-02 15:08:04.053 INFO 7972 --- [ Thread-2] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
*
* Process finished with exit code 0
*/
}