文章目录
mybatis-plus
官网:https://mp.baomidou.com/guide/
国产的开源框架,基于MyBatis
核心功能就是简化 MyBatis 的开发,提高效率。
MyBatis Plus 快速上手
Spring Boot(2.3.0) + MyBatis Plus(国产的开源框架,并没有接入到 Spring 官方孵化器中)
2、pom.xml 引入 MyBatis Plus 的依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1.tmp</version>
</dependency>
3、创建实体类
package com.monkey.mybatisplus.entity;
import lombok.Data;
@Data
public class User {
private Integer id;
private String name;
private Integer age;
}
4、创建 Mapper 接口
package com.monkey.mybatisplus;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.monkey.mybatisplus.entity.User;
public interface UserMapper extends BaseMapper<User>{
}
5、application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl //打印sql日志
6、启动类需要添加 @MapperScan(“mapper所在的包”),否则无法加载 Mppaer bean。
@SpringBootApplication
@MapperScan("com.monkey.mybatisplus.mapper")
public class MybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisplusApplication.class, args);
}
}
7、测试
package com.monkey.mybatisplus;
import com.monkey.mybatisplus.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
void test(){
userMapper.selectList(null).forEach(System.out::println);
}
}
常用注解
@TableName
映射数据库的表名(如果实体类名和数据库表名不一致)
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName(value = "user")
public class Account {
private Integer id;
private String name;
private Integer age;
}
@TableId
设置主键映射,value 映射主键字段名
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
@Data
public class User {
@TableId(value = "id")
private Integer num;
private String name;
private Integer age;
}
type
设置主键类型,主键的生成策略
@Data
public class User {
@TableId(type = IdType.AUTO)
private Long id;
@TableField(value = "name")
private String title;
private Integer age;
}
AUTO(0),
NONE(1),
INPUT(2),
ASSIGN_ID(3),
ASSIGN_UUID(4),
/** @deprecated */
@Deprecated
ID_WORKER(3),
/** @deprecated */
@Deprecated
ID_WORKER_STR(3),
/** @deprecated */
@Deprecated
UUID(4);
值 | 描述 |
---|---|
AUTO | 数据库自增 |
NONE | MP set 主键,雪花算法实现(默认) |
INPUT | 需要开发者手动赋值 |
ASSIGN_ID | MP 分配 ID,Long、Integer、String |
ASSIGN_UUID | 分配 UUID,Strinig |
INPUT
如果开发者没有手动赋值,则数据库通过自增的方式给主键赋值,如果开发者手动赋值,则存入该值。
AUTO
默认就是数据库自增,开发者无需赋值。
ASSIGN_ID MP
自动赋值,雪花算法。
ASSIGN_UUID
主键的数据类型必须是 String,自动生成 UUID 进行赋值。
@TableField
映射非主键字段,value 映射字段名
exist
表示是否为数据库字段 false,如果实体类中的成员变量在数据库中没有对应的字段,则可以使用 exist,在VO、DTO用得较多。
@Data
public class User {
@TableId(type = IdType.AUTO)
private Long id;
@TableField(value = "name")
private String title;
private Integer age;
@TableField(exist = false)
private String gender;
}
select
表示是否查询该字段
@Data
public class User {
@TableId(type = IdType.AUTO)
private Long id;
@TableField(value = "name",select = false)
private String title;
private Integer age;
@TableField(exist = false)
private String gender;
}
fill
表示是否自动填充,将对象存入数据库的时候,由 MyBatis Plus 自动给某些字段赋值,create_time、update_time
1、给表添加 create_time、update_time 字段
2、实体类中添加成员变量
package com.monkey.mybatisplus.entity;
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.Data;
import java.util.Date;
@Data
public class User {
@TableId(type = IdType.AUTO)
private Long id;
@TableField(value = "name",select = false)
private String title;
private Integer age;
@TableField(exist = false)
private String gender;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
// private Product product;
}
3、创建自动填充处理器(自动填充时间-接上INSERT INSERT_UPDATE)
package com.monkey.mybatisplus.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
@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 字段来保证数据的安全性,当修改数据的时候,会以 version 作为条件,当条件成立的时候才会修改成功。
version = 2
线程 1:update … set version = 2 where version = 1
线程2 :update … set version = 2 where version = 1
1、数据库表添加 version 字段,默认值为 1
2、实体类添加 version 成员变量,并且添加 @Version
package com.monkey.mybatisplus.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.util.Date;
@Data
public class User {
@TableId(type = IdType.AUTO)
private Long id;
@TableField(value = "name",select = false)
private String title;
private Integer age;
@TableField(exist = false)
private String gender;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
@Version //乐观锁
private Integer version;
// private Product product;
}
3、注册配置类(让乐观锁生效)
package com.monkey.mybatisplus.config;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisPlusConfig {
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
}
测试:
package com.monkey.mybatisplus;
import com.monkey.mybatisplus.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
void test(){
userMapper.selectList(null).forEach(System.out::println);
}
@Test
void update(){
// update ... version = 3 where version = 2
User user = mapper.selectById(7);
user.setTitle("一号");
// update ... version = 3 where version = 2
User user = mapper.selectById(7);
user.setTitle("二号");
mapper.updateById(user1); //乐观锁保证修改只执行一次
mapper.updateById(user);
}
}
@EnumValue
1、通用枚举类注解
,将数据库字段映射成实体类的枚举类型成员变量
package com.monkey.mybatisplus.enums;
import com.baomidou.mybatisplus.annotation.EnumValue;
public enum StatusEbum {
WORK(1,"上班"),
REST(0,"休息");
StatusEbum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
@EnumValue
private Integer code;
private String msg;
}
package com.monkey.mybatisplus.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.monkey.mybatisplus.enums.StatusEbum;
import lombok.Data;
import java.util.Date;
@Data
public class User {
@TableId(type = IdType.AUTO)
private Long id;
@TableField(value = "name",select = false)
private String title;
private Integer age;
@TableField(exist = false)
private String gender;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
@Version
private Integer version;
private StatusEbum status;
// private Product product;
}
application.yml
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl //打印sql日志
type-enums-package:
com.monkey.mybatisplus.enums //扫描枚举的包
2、实现接口
方式
package com.monkey.mybatisplus.enums;
import com.baomidou.mybatisplus.core.enums.IEnum;
public enum AgeEnum implements IEnum<Integer> {
ONE(1,"一岁"),
TWO(2,"两岁"),
THREE(3,"三岁");
private Integer code;
private String msg;
AgeEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
@Override
public Integer getValue() {
return this.code;
}
}
@TableLogic
映射逻辑删除(假删除)
1、数据表添加 deleted 字段
2、实体类添加注解
package com.monkey.mybatisplus.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.monkey.mybatisplus.enums.AgeEnum;
import com.monkey.mybatisplus.enums.StatusEbum;
import lombok.Data;
import java.util.Date;
@Data
public class User {
@TableId(type = IdType.AUTO)
private Long id;
@TableField(value = "name",select = false)
private String title;
// private AgeEnum age;
private Integer age;
@TableField(exist = false)
private String gender;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
@Version
private Integer version;
private StatusEbum status;
@TableLogic
private Integer deleted;
// private Product product;
}
3、application.yml 添加配置
global-config:
db-config:
logic-not-delete-value: 0
logic-delete-value: 1
查询
@Test
void select(){
//不加任何条件直接全部查询
// userMapper.selectList(null);
QueryWrapper wrapper = new QueryWrapper();
// wrapper.eq("name","梅西2");
// Map<String,Object> map = new HashMap<>();
// map.put("name","梅西2");
// map.put("age",18);
// wrapper.allEq(map);
// wrapper.lt("age",6);//小于
// wrapper.gt("age",6);//大于
// wrapper.ne("name","梅西2");//不等于
// wrapper.ge("age",5);//大于等于
// wrapper.like("name","西");//模糊查询
//like '%西'
// wrapper.likeLeft("name","西");//模糊查询
//like '西%'
// wrapper.likeRight("name","西");//模糊查询
//inSQL联合查询
// wrapper.inSql("id","select id from user where id < 10");
// wrapper.inSql("age","select age from user where age > 3");
// wrapper.orderByDesc("age");
wrapper.orderByAsc("age");
wrapper.having("id > 8");
System.out.println(userMapper.selectList(wrapper));
}
@Test
void select2(){
// System.out.println(userMapper.selectById(1));
// userMapper.selectBatchIds(Arrays.asList(1,2,3).forEach(System.out::println););
//Map 只能做等值判断,逻辑判断需要使用 Wrapper 来处理
// Map<String,Object> map = new HashMap<>();
// map.put("id",1);
// userMapper.selectByMap(map);
// QueryWrapper wrapper = new QueryWrapper();
// wrapper.gt("id",1);
// System.out.println(userMapper.selectCount(wrapper));
//下面将查询的结果集封装到Map中
// userMapper.selectMaps(wrapper).forEach(System.out::println);
// userMapper.selectList(wrapper).forEach(System.out::println);
//分页
// Page<User> page = new Page<>(1,5);
// Page<User> result = userMapper.selectPage(page, null);
// System.out.println(result.getSize());
// System.out.println(result.getTotal());
// System.out.println(result.getRecords().forEach(System.out::println););
//将结果封装到Map中
// Page<Map<String,Object>> page = new Page<>(1,2); //第一页,每一页两条记录
// userMapper.selectMapsPage(page,null).getRecords().forEach(System.out::println);
//返回ids
// userMapper.selectObjs(null).forEach(System.out::println);
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("id",1);
System.out.println(userMapper.selectOne(wrapper));
}
自定义 SQL(多表关联查询)
package com.monkey.mybatisplus.vo;
import lombok.Data;
@Data
public class ProductVo {
private Integer category;
private Integer count;
private String description;
private Integer userId;
private String userName;
}
package com.monkey.mybatisplus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.monkey.mybatisplus.entity.User;
import com.monkey.mybatisplus.vo.ProductVo;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserMapper extends BaseMapper<User>{
@Select("select p.*,u.name userName from product p,user u where p.user_id = u.id and u.id = #{id}")
List<ProductVo> productList(Integer id);
}
@Test
void product(){
userMapper.productList(1).forEach(System.out::println);
}
添加
@Test
void save(){
User u = new User();
u.setTitle("孙悟空");
u.setAge(18);
userMapper.insert(u);
System.out.println(u);
}
删除
@Test
void delete(){
// userMapper.deleteById(1);
// userMapper.deleteBatchIds(Arrays.asList(1,2));
// QueryWrapper wrapper = new QueryWrapper();
// wrapper.eq("age",14);
// userMapper.delete(wrapper);
Map<String,Object> map = new HashMap<>();
map.put("id",10);
userMapper.deleteByMap(map);
}
修改
@Test
void update(){
// User user = userMapper.selectById(1);
// user.setTitle("梅西2");
// userMapper.updateById(user);
// //update ... version = 3 where version = 2
// User user = mapper.selectById(1);
// user.setTitle("一号");
//
// //update ... version = 3 where version = 2
// User user1 = mapper.selectById(1);
// user1.setTitle("二号");
//
// userMapper.updateById(user1);
// userMapper.updateById(user);
User user = userMapper.selectById(1);
user.setTitle("小红");
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("age",18);
userMapper.update(user,wrapper);
}
MyBatisPlus自动生成
根据数据表自动生成实体类、Mapper、Service、ServiceImpl、Controller。
1、pom.xml 导入 MyBatis Plus Generator
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1.tmp</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
Velocity(默认)、Freemarker、Beetl
2、启动类
package com.monkey.mybatisplus;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
public class Generator {
public static void main(String[] args) {
//创建generator对象
AutoGenerator autoGenerator = new AutoGenerator();
//数据源
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL);
dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai");
dataSourceConfig.setUsername("root");
dataSourceConfig.setPassword("123456");
dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
autoGenerator.setDataSource(dataSourceConfig);
//全局配置
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setOutputDir(System.getProperty("user.dir")+"/src/main/java");
globalConfig.setOpen(false); //创建好之后不打开文件夹
globalConfig.setAuthor("hhhmonkey");
globalConfig.setServiceName("%sService"); //去掉Impl前面的I
autoGenerator.setGlobalConfig(globalConfig);
//包信息
PackageConfig packageConfig = new PackageConfig();
packageConfig.setParent("com.monkey.mybatisplus");
packageConfig.setModuleName("your");
packageConfig.setController("controller");
packageConfig.setService("service");
packageConfig.setServiceImpl("service.impl");
packageConfig.setMapper("mapper");
packageConfig.setEntity("entity");
autoGenerator.setPackageInfo(packageConfig);
//配置策略
StrategyConfig strategyConfig = new StrategyConfig();
// strategyConfig.setInclude("user","product"); //默认生成所有表,这里设置只生成部分表
strategyConfig.setInclude("user");
strategyConfig.setEntityLombokModel(true); //自动添lombok注解
strategyConfig.setNaming(NamingStrategy.underline_to_camel);
strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel); //驼峰命名
autoGenerator.setStrategy(strategyConfig);
autoGenerator.execute();
}
}
运行Generator的main方法,可得到自动生成的代码结构如下图所示:
在UserController中写一个接口测试:
package com.monkey.mybatisplus.your.controller;
import com.monkey.mybatisplus.your.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
/**
* <p>
* 前端控制器
* </p>
*
* @author hhhmonkey
* @since 2020-08-19
*/
@Controller
@RequestMapping("/your/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/index")
public ModelAndView index(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
modelAndView.addObject("list",userService.list());
return modelAndView;
}
}
application.yml:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
index.html:
<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table>
<tr th:each="user:${list}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
</tr>
</table>
</body>
</html>
运行Spring boot应用:
在浏览器查看结果:
Spring Boot +MyBatis Plus 打包,发布阿里云
本文是在视频学习过程中边学习边敲的,如有错误欢迎指正,阿里云部分可去学习B站楠哥教学视频,这里也顺便帮楠哥宣传一下,讲课辛苦了,感谢楠哥。
获取代码地址见下GitHub链接
(可参照代码看本篇文章,然后自己动手写,加油!)