SpringBoot整合MybatisPlus 生成代码(二)

本文介绍了如何使用MyBatis-Plus进行数据库操作,并通过示例展示了整合SpringBoot、配置数据源、设置全局配置、包配置、策略配置等步骤。此外,还详细解释了代码生成类的实现过程,包括模块名、表名的输入以及生成的文件结构。最后,文章提供了一个简单的部门管理API的示例,通过@RestController和@Autowired注解实现数据的获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概述

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

版本依赖

  • JDK 1.8

  • SpringBoot 2.5.1

  • Mybatis-Plus 3.4.3.1

数据库:

DROP TABLE IF EXISTS `departments`;
CREATE TABLE `departments` (
  `dept_no` char(4) NOT NULL,
  `dept_name` varchar(40) NOT NULL,
  PRIMARY KEY (`dept_no`),
  UNIQUE KEY `dept_name` (`dept_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

整合MybatisPus

application.xml配置文件

server:
  port: 8082
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF-8&useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
# 配置mybatis-plus
mybatis-plus:
  # 配置扫描xml
  mapper-locations:
    - classpath:mapper/springbootmybatisplus/*.xml
  # 实体扫描,多个package用逗号或者分号分隔
  type-aliases-package: com.kang.springbootmybatisplus.entity
  global-config:
    # 逻辑删除配置
    logic-delete-value: 0
    logic-not-delete-value: 1
#    sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
  mvc:
    view:
      prefix: /templates/
      suffix: .html

代码生成类

package com.kang.springbootmybatisplus.util;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CodeGeneration {

        public static String scanner(String tip) {
            Scanner scanner = new Scanner(System.in);
            StringBuilder help = new StringBuilder();
            help.append("请输入" + tip + ":");
            System.out.println(help.toString());
            if (scanner.hasNext()) {
                String ipt = scanner.next();
                if (StringUtils.isNotBlank(ipt)) {
                    return ipt;
                }
            }
            throw new MybatisPlusException("请输入正确的" + tip + "!");
        }

        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.setServiceName("%sService");//service 命名方式
            gc.setServiceImplName("%sServiceImpl");//service impl 命名方式
            // 自定义文件命名,注意 %s 会自动填充表实体属性!
            gc.setMapperName("%sMapper");
            gc.setXmlName("%sMapper");
            gc.setAuthor("author");
            gc.setOpen(false);
            // gc.setSwagger2(true); 实体属性 Swagger2 注解
            mpg.setGlobalConfig(gc);

            // 数据源配置
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8");
            // dsc.setSchemaName("public");
            dsc.setDriverName("com.mysql.cj.jdbc.Driver");//com.mysql.jdbc.Driver
            dsc.setUsername("root");dsc.setPassword("123456");
            mpg.setDataSource(dsc);

            // 包配置
            PackageConfig pc = new PackageConfig();
            pc.setModuleName(scanner("模块名"));
            pc.setParent("com.kang");//springbootmybatisplus
            mpg.setPackageInfo(pc);

            // 自定义配置
            InjectionConfig cfg = new InjectionConfig() {
                @Override
                public void initMap() {
                    // to do nothing
                }
            };

            // 如果模板引擎是 freemarker
            String templatePath = "/templates/mapper.xml.ftl";
            // 如果模板引擎是 velocity
            // String templatePath = "/templates/mapper.xml.vm";

            // 自定义输出配置
            List<FileOutConfig> focList = new ArrayList<>();
            // 自定义配置会被优先输出
            focList.add(new FileOutConfig(templatePath) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                    return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                            + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                }
            });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录");
                return false;
            }
        });
        */
            cfg.setFileOutConfigList(focList);
            mpg.setCfg(cfg);

            // 配置模板
            TemplateConfig templateConfig = new TemplateConfig();

            // 配置自定义输出模板
            //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
            // templateConfig.setEntity("templates/entity2.java");
            // templateConfig.setService();
            // templateConfig.setController();

            templateConfig.setXml(null);
            mpg.setTemplate(templateConfig);

            // 策略配置
            StrategyConfig strategy = new StrategyConfig();
            strategy.setNaming(NamingStrategy.underline_to_camel);
            strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//        strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
            strategy.setEntityLombokModel(true);
            strategy.setRestControllerStyle(true);
//        strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
            strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
//        strategy.setSuperEntityColumns("id");
            strategy.setControllerMappingHyphenStyle(true);
            strategy.setTablePrefix(pc.getModuleName() + "_");
            mpg.setStrategy(strategy);
            mpg.setTemplateEngine(new FreemarkerTemplateEngine());
            mpg.execute();
        }

}

运行CodeGeneration.main 函数,根据控制台提示输入。

请输入模块名:
springbootmybatisplus
请输入表名,多个英文逗号分割:
departments

在项目目录中,将看到 entity、mapper、service、controller、resource/springbootmybatisplus/*Mapper.xml 目录下生成文件。

修改控制器类

@RestController
public class DepartmentsController {

    @Autowired
    private DepartmentsService departmentsService;

    @GetMapping("/api/departments")
    public List<Departments> list() throws Exception {
        return departmentsService.list();
    }

}

测试

访问:http://localhost:8082/api/departments ,输出结果如下。[{“deptNo”:“1001”,“deptName”:“A”},{“deptNo”:“1002”,“deptName”:“B”},{“deptNo”:“1003”,“deptName”:“C”},{“deptNo”:“1004”,“deptName”:“D”}]

参考

https://mp.baomidou.com/guide/

https://mp.baomidou.com/guide/generator.html#%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B

<think>嗯,用户问的是1.8版本的JDK整合MyBatis-Plus,我得先理清楚这个问题的关键点在哪里。首先,用户可能正在开发一个Java项目,使用JDK 1.8,现在想要集成MyBatis-Plus来简化数据库操作。那么,我需要考虑他们可能对整合步骤不熟悉,需要一步步指导。 首先,我需要确认MyBatis-Plus的版本兼容性。虽然大部分情况下MyBatis-Plus支持Java 8,但最好建议使用较新的稳定版,比如3.5.x,这样避免出现兼容性问题。接下来,项目的构建工具可能是Maven或者Gradle,这里应该以Maven为例,因为用户可能更熟悉,或者这是最常见的情况。 然后,整合的基本步骤应该是添加依赖、配置数据源、创建实体类和Mapper接口、配置MyBatis-Plus以及测试。用户可能需要具体的代码示例,比如如何在pom.xml中添加依赖,特别是注意MyBatis-Plus的starter和生成器依赖是否需要分开说明。数据源配置部分,用户可能使用Spring Boot,所以application.yml或application.properties的配置是必须的,这里需要给出示例,比如数据库URL、用户名、密码以及MyBatis-Plus的相关配置,比如mapper扫描路径和下划线转驼峰。 实体类部分,应该提到使用MyBatis-Plus的注解,比如@TableName和@TableId,这样用户知道如何映射数据库表。Mapper接口需要继承BaseMapper,并添加@Mapper注解或者使用@MapperScan来扫描,这里可能需要强调接口的位置,避免扫描不到的问题。 配置类可能需要用户添加分页插件,这是常用的功能,所以需要给出添加PaginationInnerInterceptor的示例,这样用户可以直接复制代码。最后,测试部分应该简单说明如何注入Mapper并调用方法,比如selectList,并确认结果。 另外,用户可能有疑问的地方包括版本冲突、配置是否正确、注解的使用是否正确,或者如何解决常见问题,比如无法找到Mapper接口。可能需要提醒检查包扫描路径,或者是否添加了必要的插件。此外,如果用户想用代码生成器,可以简要提到如何使用MyBatis-Plus的生成器模块,自动生成实体类、Mapper等代码,这样可以提高效率。 还要考虑用户是否可能在使用Spring Boot,因为MyBatis-Plus和Spring Boot整合比较常见,所以整个步骤应该基于Spring Boot项目来讲解,这样更符合实际应用场景。同时,需要确保示例代码的正确性,比如数据源配置的正确格式,避免拼写错误。 最后,用户可能需要了解更高级的功能,比如分页、乐观锁、自动填充等,但问题可能集中在基础整合上,所以先提供基本步骤,然后在扩展部分简单提及这些功能,供用户后续探索。这样回答既解决了当前问题,又引导用户进一步学习,可能更符合他们的需求。</think>在 Java 8(JDK 1.8)环境下整合 MyBatis-Plus,通常需要结合 Spring Boot 进行快速集成。以下是详细步骤和说明: --- ### **1. 环境准备** - JDK 1.8 或更高版本 - Maven 或 Gradle(以 Maven 为例) - Spring Boot(推荐 2.x 版本) - MyBatis-Plus(建议使用最新稳定版,如 `3.5.x`) -- ### **2. 添加依赖** 在 `pom.xml` 中添加 MyBatis-Plus 和数据库驱动依赖: ```xml <!-- MyBatis-Plus Starter --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.3.1</version> <!-- 使用最新版本 --> </dependency> <!-- 数据库驱动(以 MySQL 为例) --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.30</version> </dependency> <!-- 代码生成器(可选) --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.5.3.1</version> </dependency> ``` --- ### **3. 配置数据源** 在 `application.yml` 或 `application.properties` 中配置数据库连接和 MyBatis-Plus: ```yaml spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC username: root password: 123456 # MyBatis-Plus 配置 mybatis-plus: mapper-locations: classpath:mapper/**/*.xml # XML 映射文件路径 configuration: map-underscore-to-camel-case: true # 自动驼峰命名转换 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 打印 SQL 日志(调试用) ``` --- ### **4. 创建实体类和 Mapper** #### **实体类** 使用 `@TableName` 和 `@TableId` 注解映射数据库表: ```java @Data @TableName("user") // 对应数据库表名 public class User { @TableId(type = IdType.AUTO) // 主键自增 private Long id; private String name; private Integer age; private String email; } ``` #### **Mapper 接口** 继承 `BaseMapper` 并添加 `@Mapper` 注解(或通过 `@MapperScan` 全局扫描): ```java @Mapper public interface UserMapper extends BaseMapper<User> { // 无需编写基础 CRUD 方法,MyBatis-Plus 已自动实现 } ``` --- ### **5. 配置 MyBatis-Plus 插件** 在 Spring Boot 启动类或配置类中添加分页插件: ```java @Configuration public class MyBatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // 分页插件 interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } } ``` --- ### **6. 测试整合结果** 编写测试类验证 MyBatis-Plus 功能: ```java @SpringBootTest public class UserMapperTest { @Autowired private UserMapper userMapper; @Test public void testSelect() { List<User> users = userMapper.selectList(null); users.forEach(System.out::println); } } ``` -- ### **7. 扩展功能** MyBatis-Plus 还支持以下特性: 1. **代码生成器**:自动生成 Entity、Mapper、Service 代码。 2. **条件构造器**:通过 `QueryWrapper` 或 `LambdaQueryWrapper` 构建动态 SQL。 3. **乐观锁**:使用 `@Version` 注解实现版本控制。 4. **自动填充**:通过 `@TableField(fill = FieldFill.INSERT)` 自动填充时间字段。 --- ### **常见问题** 1. **依赖冲突**:确保 MyBatis-Plus 版本与 Spring Boot 兼容。 2. **Mapper 扫描失败**:检查 `@MapperScan("com.example.mapper")` 路径是否正确。 3. **SQL 不生效**:确认实体类字段与数据库表字段映射正确。 --- 通过以上步骤即可在 JDK 1.8 环境下完成 MyBatis-Plus 的整合。如果需要更高级功能,可参考 [MyBatis-Plus 官方文档](https://baomidou.com/)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值