spring boot
中配置mybatis-plus
1、创建一个spring boot
项目,注意勾选mysql
2、在pom.xml
文件中添加mybatis-plus
的依赖包
<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.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>3.1.3version>
<relativePath/>
parent>
<groupId>com.examplegroupId>
<artifactId>spring_mybatisartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>spring_mybatisname>
<description>spring_mybatisdescription>
<properties>
<java.version>17java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>com.mysqlgroupId>
<artifactId>mysql-connector-jartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.5.3.2version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>2.0.40version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.2.19version>
dependency>
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>5.8.21version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
exclude>
excludes>
configuration>
plugin>
plugins>
build>
project>
3、创建一个beego
的数据库,并且创建一个user
的表
-- ------------------------
-- 用户表
-- ------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT COMMENT '主键id',
`username` varchar(50) not null COMMENT '用户名',
`password` varchar(100) not null COMMENT '密码',
`status` tinyint(4) DEFAULT '1' COMMENT '状态,0表示禁止,1表示正常',
`created_at` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) COMMENT '创建时间',
`updated_at` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6) COMMENT '更新时间',
`deleted_at` timestamp(6) NULL DEFAULT NULL COMMENT '软删除时间'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT = "用户表";
4、在application.yml
中配置mysql
连接池及mybatis-plus
的配置
server:
port: 9000
spring:
# 数据库配置
datasource:
url: jdbc:mysql://localhost:3306/beego?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false&useAffectedRows=true&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
type: com.alibaba.druid.pool.DruidDataSource
#配置mybatis-plus信息
mybatis-plus:
configuration:
# 开启下划线转驼峰
map-underscore-to-camel-case: true
auto-mapping-behavior: full
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# mapping的路径
mapper-locations: classpath*:mapper/**/*Mapper.xml
global-config:
db-config:
#主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID", ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
id-type: AUTO
# 逻辑删除(软删除)
logic-delete-value: NOW()
logic-not-delete-value: 'NULL'
5、在spring boot
的入口文件配置要扫描的mapper
路径
package com.example.spring_mybatis;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = {"com.example.spring_mybatis.mapper"})
@Slf4j
public class SpringMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringMybatisApplication.class, args);
log.info("服务已经启动localhost:9000");
}
}
6、简单运行项目,看看是否可以正常运行
mybatis plus
一些基本的配置1、统一时间格式
package com.example.spring_mybatis.config;
import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
@Component
@Slf4j
public class LocalDateTimeFormatConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
}
2、分页器插件配置
package com.example.spring_mybatis.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;
/**
* mybatis-plus分页插件
*/
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
3、元数据配置,比如创建时间、更新时间、获取当前更新人等数据
package com.example.spring_mybatis.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.example.spring_mybatis.model.BaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;
/**
* mybatis-plus元数据插件配置(更新时间,不在数据库层面做)
*/
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
/**
* 插入时自动填充
*
* @param metaObject
*/
@Override
public void insertFill(MetaObject metaObject) {
if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
// 创建时间和更新时间
if (Objects.isNull(baseEntity.getCreatedAt())) {
baseEntity.setCreatedAt(LocalDateTime.now());
}
if (Objects.isNull(baseEntity.getUpdatedAt())) {
baseEntity.setUpdatedAt(LocalDateTime.now());
}
}
}
/**
* 更新时自动填充
*
* @param metaObject
*/
@Override
public void updateFill(MetaObject metaObject) {
if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
baseEntity.setUpdatedAt(LocalDateTime.now());
}
}
}
2、手动创建实体类去继承BaseEntity
类,在BaseEntity
类中书写一些基础字段
package com.example.spring_mybatis.model;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class BaseEntity {
@TableId(value = "id", type = IdType.AUTO)
private String id;
@TableField(fill = FieldFill.INSERT)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createdAt;
@TableField(fill = FieldFill.INSERT_UPDATE)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updatedAt;
@TableLogic
@JsonIgnore
private LocalDateTime deletedAt;
}
package com.example.spring_mybatis.model;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.time.LocalDateTime;
import java.util.Date;
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("user")
public class UserEntity extends BaseEntity{
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 状态:0是禁止,1是正常
*/
private Integer status;
}
3、控制器内容书写
package com.example.spring_mybatis.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.spring_mybatis.dto.UserDTO;
import com.example.spring_mybatis.model.UserEntity;
import com.example.spring_mybatis.service.IUserService;
import com.example.spring_mybatis.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController {
@Autowired
private IUserService iUserService;
@PostMapping("")
public R<String> createUser(@RequestBody UserDTO userDto) {
log.info("进入创建用户的控制器");
return this.iUserService.createUser(userDto);
}
@GetMapping()
public R<List<UserEntity>> getUser() {
List<UserEntity> list = this.iUserService.list();
return R.success(list);
}
@DeleteMapping("/{id}")
public R<String> deleteUserById(@PathVariable Long id){
System.out.println("接收到参数:"+id);
LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(UserEntity::getId,id);
boolean affected = iUserService.remove(queryWrapper);
if (affected) {
return R.success("删除成功");
} else {
return R.error("删除失败");
}
}
}
4、服务层接口
package com.example.spring_mybatis.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.spring_mybatis.dto.UserDTO;
import com.example.spring_mybatis.model.UserEntity;
import com.example.spring_mybatis.utils.R;
public interface IUserService extends IService<UserEntity> {
R<String> createUser(UserDTO userDto);
}
5、服务层
package com.example.spring_mybatis.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.spring_mybatis.dto.UserDTO;
import com.example.spring_mybatis.mapper.UserMapper;
import com.example.spring_mybatis.model.UserEntity;
import com.example.spring_mybatis.service.IUserService;
import com.example.spring_mybatis.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public R<String> createUser(UserDTO userDto) {
UserEntity userEntity = new UserEntity();
BeanUtils.copyProperties(userDto, userEntity);
int insert = this.userMapper.insert(userEntity);
if (insert == 1) {
return R.success("创建成功");
} else {
return R.error("创建失败");
}
}
}
6、mapper
层的书写
package com.example.spring_mybatis.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.spring_mybatis.model.UserEntity;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper extends BaseMapper<UserEntity> {
}
7、UserMapper.xml
的书写
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.spring_mybatis.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.spring_mybatis.model.UserEntity">
<result column="id" property="id"/>
<result column="created_at" property="createdAt"/>
<result column="updated_at" property="updatedAt"/>
<result column="deleted_at" property="deletedAt"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="status" property="status"/>
resultMap>
mapper>
8、运行代码,使用postman
调试是否可以创建成功
1、官方地址
2、使用上面的方式要一个一个文件夹去创建比较费力,下面讲解模板生成器的使用
3、安装依赖包
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.5.3.1version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-freemarkerartifactId>
dependency>
4、创建一个CodeGenerator
的文件
package com.example.spring_mybatis;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.CustomFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.example.spring_mybatis.model.BaseEntity;
import java.text.MessageFormat;
import java.util.*;
public class CodeGenerator {
private final static String DB_USERNAME = "root";
private final static String DB_HOST = "localhost";
private final static String DB_PORT = "3306";
private final static String DB_PASSWORD = "123456";
private final static String DB_DATABASE = "beego";
private final static String PROJECT_PATH = "com/example/spring_mybatis";
// private final static String PROJECT_PATH = System.getProperty("user.dir");
public static void main(String[] args) {
System.out.println(System.getProperty("user.dir"));
// 数据源配置
FastAutoGenerator fastAutoGenerator = FastAutoGenerator.create(MessageFormat.format("jdbc:mysql://{0}:{1}/{2}?serverTimezone=GMT%2B8", DB_HOST, DB_PORT, DB_DATABASE), DB_USERNAME, DB_PASSWORD)
// 1.全局配置
.globalConfig(builder -> {
builder.author("水痕") // 设置作者
// .enableSwagger() // 开启 swagger 模式 默认值:false
.disableOpenDir() // 禁止打开输出目录 默认值:true
.commentDate("yyyy-MM-dd HH:mm:ss") // 注释日期
.fileOverride() // 覆盖之前的文件
.dateType(DateType.ONLY_DATE) //定义生成的实体类中日期类型 DateType.ONLY_DATE 默认值: DateType.TIME_PACK
.outputDir(System.getProperty("user.dir") + "/src/main/java"); // 指定输出目录
})
// 2.包配置
.packageConfig(builder -> {
builder.parent(PROJECT_PATH.replace("/", ".")) // 父包模块名
.pathInfo(getPathInfo())
.controller("controller") //Controller 包名 默认值:controller
.entity("model") //Entity 包名 默认值:entity
.service("service") //Service 包名 默认值:service
.mapper("mapper") //Mapper 包名 默认值:mapper
// .other("model")
//.moduleName("xxx") // 设置父包模块名 默认值:无
.pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir") + "/src/main/resources/mapper")); // 设置mapperXml生成路径
//默认存放在mapper的xml下
})
// .injectionConfig(consumer -> {
// // Map customFile = new HashMap<>();
// // DTO 下面的key会作为类名后缀,进而生成新类
customFile.put("DTO.java", "templates/other/dto.java.vm");
customFile.put("VO.java", "templates/other/vo.java.vm");
consumer.customFile(customFile);
// String basePath = System.getProperty("user.dir");
// List customFiles = new ArrayList<>();
// customFiles.add(new CustomFile.Builder().fileName("DTO.java")
// .templatePath("templates/other/dto.java.vm")
// .filePath(basePath+"/src/main/java/"+PROJECT_PATH+"/dto").build());
// customFiles.add(new CustomFile.Builder().fileName("VO.java")
// .templatePath("templates/other/vo.java.vm")
// .filePath(basePath+"/src/main/java/"+PROJECT_PATH+"/vo").build());
// consumer.customFile(customFiles);
//
// })
// 策略配置
.strategyConfig(builder -> {
builder.addInclude(scanner("表名,多个英文逗号分割").split(","))
//service策略配置
.serviceBuilder()
.formatServiceFileName("I%sService")
.formatServiceImplFileName("%sServiceImpl")
// 实体类策略配置
.entityBuilder()
.formatFileName("%sEntity")
// .idType(IdType.ASSIGN_ID)//主键策略 雪花算法自动生成的id
// .addTableFills(new Column("created_at", FieldFill.INSERT)) // 自动填充配置
// .addTableFills(new Property("updated_at", FieldFill.INSERT_UPDATE))
.enableLombok() //开启lombok
// .logicDeleteColumnName("deleted_at")// 说明逻辑删除是哪个字段
// .formatFileName("%sEntity")
.superClass(BaseEntity.class)
.addSuperEntityColumns("id", "created_at", "updated_at", "deleted_at") // 公共字段不需要抽取
.enableTableFieldAnnotation()// 属性加上注解说明
// 关于控制器的
.controllerBuilder() //controller 策略配置
.formatFileName("%sController")
.enableRestStyle() // 开启RestController注解
// 关于mapper的
.mapperBuilder()// mapper策略配置
.formatMapperFileName("%sMapper")
// .enableMapperAnnotation()//@mapper注解开启
.formatXmlFileName("%sMapper");
}).templateEngine(new FreemarkerTemplateEngine());
// 使用Freemarker引擎模板,默认的是Velocity引擎模板
//
fastAutoGenerator.execute();
System.out.println("生成模板成功");
}
private static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help);
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
/**
* 配置生成路径
*
* @return
*/
private static Map<OutputFile, String> getPathInfo() {
Map<OutputFile, String> pathInfo = new HashMap<>();
String path = "/src/main/java/" + PROJECT_PATH;
pathInfo.put(OutputFile.entity, System.getProperty("user.dir") + path + "/model");
pathInfo.put(OutputFile.mapper, System.getProperty("user.dir") + path + "/mapper");
pathInfo.put(OutputFile.service, System.getProperty("user.dir") + path + "/service");
pathInfo.put(OutputFile.serviceImpl, System.getProperty("user.dir") + path + "/service/impl");
pathInfo.put(OutputFile.controller, System.getProperty("user.dir") + path + "/controller");
pathInfo.put(OutputFile.xml, System.getProperty("user.dir") + "/src/main/resources/mapper");
return pathInfo;
}
}
5、运行文件输入表名,一件生成上面的代码文件
1、导入依赖包
<dependency>
<groupId>org.hibernate.validatorgroupId>
<artifactId>hibernate-validatorartifactId>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.5.3.1version>
dependency>
<dependency>
<groupId>org.apache.velocitygroupId>
<artifactId>velocity-engine-coreartifactId>
<version>2.3version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-freemarkerartifactId>
dependency>
2、直接参考代码,代码见