官方文档
https://mp.baomidou.com/
创建SpringBoot项目,添加以下依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
这里用的版本是3.0.5,需要新版可以参照官方文档快速入门
数据库
Sql代码
use mybatisPlus;
drop table if exists user;
create table user
(
id bigint(20) not null comment '主键ID',
name varchar(30) null default null comment '姓名',
age int(11) null default null comment '年龄',
email varchar(50) null default null comment '邮箱',
primary key(id)
);
insert into user(id,name,age,email) values
(1,'Jone',18,'test1qq.com'),
(2,'Jack',20,'test2qq.com'),
(3,'Tom',28,'test3qq.com'),
(4,'Sandy',21,'test4qq.com'),
(5,'Billie',24,'test5qq.com');
-- 设置主键自增
ALTER TABLE `mybatisplus`.`user`
CHANGE COLUMN `id` `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID' ;
-- 增加创建和更新时间字段
ALTER TABLE `mybatisplus`.`user`
ADD COLUMN `create_time` DATETIME NULL COMMENT '创建时间' AFTER `email`,
ADD COLUMN `update_time` DATETIME NULL COMMENT '更新时间' AFTER `create_time`;
-- 增加乐观锁
ALTER TABLE `mybatisplus`.`user`
ADD COLUMN `version` INT(10) NULL DEFAULT 1 COMMENT '乐观锁' AFTER `email`;
-- 增加逻辑删除字段
ALTER TABLE `mybatisplus`.`user`
ADD COLUMN `deleted` INT(1) NULL DEFAULT 0 COMMENT '逻辑删除' AFTER `version`;
POJO(Entity)实体类
package com.zzf.mybatis_plus.pojo;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/*
*
*@author:zzf
*@time:2021-01-19
*
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@TableId(type=IdType.AUTO)//可设置不同的主键策略,默认是雪花算法
private Integer id;
private String name;
private Integer age;
private String email;
@Version//乐观锁(每次更新先查询version值,在此基础上比较和加1,如果多线程可能会出现更新失败)
private Integer version;
@TableLogic//逻辑删除
private Integer deleted;
@TableField(fill = FieldFill.INSERT)//自动填充
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)//自动填充
private Date updateTime;
}
要实现自动填充,需要添加handler
package com.zzf.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;
/*
*
*@author:zzf
*@time:2021-01-20
*
*/
@Slf4j
@Component//放进IOC容器
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill....");//插入时填充
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill....");//更新时填充
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
添加相关插件的所需的配置类
package com.zzf.mybatis_plus.config;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.apache.ibatis.annotations.Property;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/*
*
*@author:zzf
*@time:2021-01-20
*
*/
@MapperScan("com.zzf.mybatis_plus.mapper")
@EnableTransactionManagement
@Configuration//配置类
public class MyBatisPlusConnfig {
//乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
//分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
//逻辑删除组件
//逻辑删除是为了方便数据恢复和保护数据本身价值等等的一种方案
@Bean
public ISqlInjector sqlInjector(){
return new LogicSqlInjector();
}
@Bean
@Profile({
"dev","test"})
public PerformanceInterceptor performanceInterceptor(){
PerformanceInterceptor performanceInterceptor=new PerformanceInterceptor();
performanceInterceptor.setMaxTime(1000);//设置sql执行的最大时间,如果超过了则不执行
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
}
配置文件application.properties
##配置开发环境
spring.profiles.active=dev
# 应用名称
spring.application.name=mybatis_plus
# 应用服务 WEB 访问端口
server.port=8080
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatisPlus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#配置日志
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
持久层
package com.zzf.mybatis_plus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zzf.mybatis_plus.pojo.User;
import org.springframework.stereotype.Repository;
/*
*
*@author:zzf
*@time:2021-01-19
*
*/
@Repository//代表持久层
public interface UserMapper extends BaseMapper<User> {
}
简单CRUD测试
package com.zzf.mybatis_plus;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzf.mybatis_plus.mapper.UserMapper;
import com.zzf.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.Arrays;
import java.util.HashMap;
import java.util.List;
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
//查询全部用户,参数为Wrapper条件构建器,先设为null
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
//测试插入
@Test
void testInsert(){
User user=new User();
user.setName("aaaaaBO");
user.setAge(18);
user.setEmail("[email protected]");
userMapper.insert(user);
}
//测试更新
@Test
void testUpdate(){
User user=new User();
//通过条件自动拼装动态sql
user.setId(8);
user.setName("HHHa");
user.setAge(22);
int i=userMapper.updateById(user);
System.out.println(i);
}
//测试乐观锁(单线程)
@Test
public void testOptimisticLocker(){
//查询用户信息
User user=userMapper.selectById(8L);
//修改
user.setName("Kkkkg");
user.setEmail("[email protected]");
userMapper.updateById(user);
}
//测试乐观锁(多线程)
@Test
void testOptimisticLocker2(){
//线程1
User user=userMapper.selectById(8L);
user.setName("zzf");
user.setEmail("[email protected]");
//模拟另外一线程执行了插队操作
User user2=userMapper.selectById(8L);
user2.setName("zzzf");
user2.setEmail("[email protected]");
userMapper.updateById(user2);
userMapper.updateById(user);
}
//测试查询ById
@Test
void testSelectById(){
User user =userMapper.selectById(8L);
System.out.println(user);
}
//测试批量查询
@Test
void testSelectByBatchId(){
List<User> users=userMapper.selectBatchIds(Arrays.asList(6,7,8));
users.forEach(System.out::println);
}
//测试按条件查询By map
@Test
void testSelectByMap(){
HashMap<String, Object> map = new HashMap();
map.put("name","zzzf");
map.put("age",22);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
//测试分页查询
@Test
void testPage(){
//参数1:当前页,页面大小
//参数2:页面大小
Page<User> page = new Page<>(2, 5);
userMapper.selectPage(page,null);
}
//测试删除
@Test
void testDeleteById(){
userMapper.deleteById(1);
}
//通过id批量删除
@Test
void testDeleteBatchById(){
userMapper.deleteBatchIds(Arrays.asList(2,3));
}
//通过Map删除
@Test
void testDeleteByMap(){
HashMap<String, Object> map=new HashMap<>();
map.put("name","JoLin");
userMapper.deleteByMap(map);
}
//测试逻辑删除
@Test
void tsetLogicDelete(){
userMapper.deleteById(5);
}
}
基于条件构造器的测试
package com.zzf.mybatis_plus;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzf.mybatis_plus.mapper.UserMapper;
import com.zzf.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;
/*
*
*@author:zzf
*@time:2021-01-20
*
*/
@SpringBootTest
public class WrapperTest {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads(){
//查询name不为空的用户,并且邮箱不为空,年龄大于等于12
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper.isNotNull("name")
.isNotNull("email")
.ge("age",21);
userMapper.selectList(wrapper).forEach(System.out::println);
}
//查询一个结果
@Test
void test2(){
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper.eq("name","JOBO");
User user=userMapper.selectOne(wrapper);
System.out.println(user);
}
//查询结果数量
@Test
void test3(){
//查询年龄在20-30岁之间的用户
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper.between("age",20,30);//区间
Integer count = userMapper.selectCount(wrapper);
System.out.println(count);
}
//模糊查询
@Test
void test4(){
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper.notLike("name","e")//不包含e
.likeRight("email","t");//以t开头,即t%
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
//子查询
@Test
void test5(){
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper.inSql("id","select id from user where id>3");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
//排序查询
@Test
void test6(){
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper.orderByDesc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
}
代码生成器
先添加相关依赖
<!-- https://mvnrepository.com/artifact/com.spring4all/swagger-spring-boot-starter -->
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generator -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
package util;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
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.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
/*
*
*@author:zzf
*@time:2021-01-20
*
*/
public class GenerateCode {
public static void main(String[] args) {
//构建代码自动生成器对象
AutoGenerator mpg=new AutoGenerator();
//配置策略
//全局配置
GlobalConfig gc=new GlobalConfig();
String projectPath=System.getProperty("user.dir");
gc.setOutputDir(projectPath+"/src/main/java");
gc.setAuthor("zzf");
gc.setOpen(false);
gc.setFileOverride(false);//是否覆盖
gc.setServiceName("%sService");//去掉I前缀
gc.setIdType(IdType.AUTO);
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
//设置数据源
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/mybatisPlus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
dataSourceConfig.setUsername("root");
dataSourceConfig.setPassword("123456");
dataSourceConfig.setDbType(DbType.MYSQL);
mpg.setDataSource(dataSourceConfig);
//包配置
PackageConfig packageConfig = new PackageConfig();
packageConfig.setModuleName("plus_test");
packageConfig.setParent("com.zzf.mybatis_plus");
packageConfig.setEntity("entity");
packageConfig.setMapper("mapper");
packageConfig.setService("service");
packageConfig.setController("controller");
mpg.setPackageInfo(packageConfig);
//策略配置
StrategyConfig strategyConfig=new StrategyConfig();
strategyConfig.setInclude("user");//要映射的表,可传多个参数表示多张表
strategyConfig.setNaming(NamingStrategy.underline_to_camel);
strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
strategyConfig.setEntityLombokModel(true);//自动lombok
strategyConfig.setLogicDeleteFieldName("deleted");//逻辑删除
//自动填充配置
TableFill createTime=new TableFill("create_time", FieldFill.INSERT);
TableFill updateTime=new TableFill("update_time", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills=new ArrayList<>();
tableFills.add(updateTime);
tableFills.add(createTime);
strategyConfig.setTableFillList(tableFills);
//乐观锁
strategyConfig.setVersionFieldName("version");
//controller风格
strategyConfig.setRestControllerStyle(true);
mpg.setStrategy(strategyConfig);
mpg.execute();
}
}
使用后能自动生成entity、mapper、service、controller层的代码
参考:
https://www.bilibili.com/video/BV17E411N7KN