一、在spring boot
中配置mybatis-plus
-
1、创建一个
spring boot
项目,注意勾选mysql
-
2、在
pom.xml
文件中添加mybatis-plus
的依赖包<?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>3.1.3</version> <relativePath/> </parent> <groupId>com.example</groupId> <artifactId>spring_mybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring_mybatis</name> <description>spring_mybatis</description> <properties> <java.version>17</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- mybatis-plus依赖包 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.3.2</version> </dependency> <!-- 处理json的 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>2.0.40</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.19</version> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.21</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </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()); } } }
三、手动搭建控制器、服务层、实体类
- 1、最终项目目录结构如下
-
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
的书写<?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.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、安装依赖包
<!-- mybatis-plus代码生成器 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.5.3.1</version> </dependency> <!-- 代码生成器的模板 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </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<String, String> 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<CustomFile> 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.validator</groupId> <artifactId>hibernate-validator</artifactId> </dependency> <!-- mybatis-plus代码生成器 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.5.3.1</version> </dependency> <!-- 自动生成模板需要 --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.3</version> </dependency> <!-- 代码生成器的模板 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
-
2、直接参考代码,代码见