SpringBoot 之 mybatis-plus 代码生成器,xml 文件生成在 resource 文件下

文章展示了如何配置一个基于SpringBoot的项目,依赖于MyBatisPlus和Druid,用于数据库连接。同时,它包含了代码自动生成器的配置,使用了FreeMarker和Velocity模板引擎,以及如何进行数据源、全局、包、策略和模板的定制,以自动生成Java实体、Mapper接口和服务代码。

相关依赖:

<?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>2.7.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>ai.springboot</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot</name>
    <description>springboot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </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>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.14</version>
        </dependency>

        <!-- 代码自动生成器依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</version>
        </dependency>

        <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>

        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-commons</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.7.5</version>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

生成代码

package ai.springboot.common;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
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.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.platform.commons.util.StringUtils;

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


public class CodeGenerator {


    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")+"/springboot";//注意这个加号后面的字符串是对应的模块名称如果你使用的是前后端分离项目那么要加上这串字符串如果不是不加即可
        gc.setOutputDir(projectPath + "/src/main/java");//设置代码生成路径
        gc.setFileOverride(true);//是否覆盖以前文件
        gc.setOpen(false);//是否打开生成目录
        gc.setAuthor("aishuangpeng");//设置项目作者名称
        gc.setIdType(IdType.AUTO);//设置主键策略
        gc.setBaseResultMap(true);//生成基本ResultMap
        gc.setBaseColumnList(true);//生成基本ColumnList
        gc.setServiceName("%sService");//去掉服务默认前缀
        gc.setDateType(DateType.ONLY_DATE);//设置时间类型
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/wms?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("1234");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("ai.springboot");
        pc.setMapper("mapper");
//        pc.setXml("mapper.xml");
        pc.setEntity("entity");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setController("controller");
        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/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

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

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


        // 策略配置
        StrategyConfig sc = new StrategyConfig();
        sc.setNaming(NamingStrategy.underline_to_camel);
        sc.setColumnNaming(NamingStrategy.underline_to_camel);
        sc.setEntityLombokModel(true);//自动lombok
        sc.setRestControllerStyle(true);
        sc.setControllerMappingHyphenStyle(true);

        sc.setLogicDeleteFieldName("deleted");//设置逻辑删除

        //设置自动填充配置
        TableFill gmt_create = new TableFill("create_time", FieldFill.INSERT);
        TableFill gmt_modified = new TableFill("update_time", FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills=new ArrayList<>();
        tableFills.add(gmt_create);
        tableFills.add(gmt_modified);
        sc.setTableFillList(tableFills);

        //乐观锁
        sc.setVersionFieldName("version");
        sc.setRestControllerStyle(true);//驼峰命名



        //  sc.setTablePrefix("tbl_"); 设置表名前缀
        sc.setInclude(scanner("表名,多个英文逗号分割").split(","));
        mpg.setStrategy(sc);

        // 生成代码
        mpg.execute();
    }

}

### Spring Boot 整合 MyBatis-Plus 实现用户登录和注册 CRUD 操作 #### 创建 Spring Boot 项目并引入依赖 为了在 Spring Boot 中集成 MyBatis-Plus 并实现用户的增删查改操作,首先需要创建一个新的 Spring Boot 工程,并添加必要的 Maven 依赖。 ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> <!-- MySQL Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> ``` 这些依赖项用于支持 MyBatis-Plus 功能以及连接到 MySQL 数据库[^1]。 #### 配置数据库连接信息 编辑 `application.yml` 文件以设置数据库的相关参数: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver ``` 此部分配置指定了要使用的数据库 URL、用户名、密码以及其他驱动程序选项。 #### 定义实体类 UserEntity 基于数据库中的 user 表定义相应的 Java 类型映射对象 (POJO),即 `UserEntity.java`: ```java package com.example.demo.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; @Data @TableName("user") public class UserEntity { private Long id; // 主键 @TableField("username") private String userName; @TableField("password") private String passWord; } ``` 这里使用了 Lombok 库来自动生成 getter/setter 方法;同时利用 MyBatis-Plus 提供的注解来指定表名及字段名称对应关系[^3]。 #### 编写 Mapper 接口 IUserMapper 接着编写一个接口继承自 `BaseMapper<T>` 来获取默认提供的基本方法,比如 insert(), deleteById() 等等。对于本案例而言就是 `IUserMapper.java` : ```java package com.example.demo.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.demo.entity.UserEntity; import org.apache.ibatis.annotations.Mapper; @Mapper public interface IUserMapper extends BaseMapper<UserEntity> {} ``` 上述代码声明了一个名为 `IUserMapper` 的接口,该接口扩展了 MyBatis-Plus 内建的基础持久层接口 `BaseMapper`,从而可以直接访问底层的数据存储服务而无需额外的手动SQL语句书写工作。 #### Service 层逻辑封装 UserServiceImpl 为了让业务更加清晰分离,在 service 层中进一步抽象具体的业务流程处理细节。新建文件夹 service 下面建立两个文件:UserService.java 和它的实现类 UserServiceImpl.java 。其中前者仅需申明一些公共的方法签名即可,后者则负责具体的功能实现。 ```java @Service public class UserServiceImpl implements IService<UserEntity> { @Autowired private IUserMapper iUserMapper; public boolean register(String name, String pwd){ int count = this.iUserMapper.selectCount(new QueryWrapper<UserEntity>().eq("username",name)); if(count != 0){return false;} UserEntity entity=new UserEntity(); entity.setUserName(name); entity.setPassWord(pwd); return this.save(entity); } public UserEntity login(String name, String pwd){ LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(UserEntity::getUserName,name).eq(UserEntity::getPassWord,pwd); return this.getOne(queryWrapper); } } ``` 这段代码展示了如何通过调用 mapper 层所提供的 API 来完成新增记录的操作(`register`) ,同时也演示了查询特定条件下的唯一结果 (`login`). 使用 lambda 方式的构造器能够使表达式更为简洁直观[^2]. #### Controller 控制器接收 HTTP 请求 最后一步就是在控制器里边暴露 RESTful API 给前端应用调用了。同样地也需要先定义好接口规范再着手于实际功能模块的设计与开发。 ```java @RestController @RequestMapping("/api/user") public class UserController { @Resource private UserService userService; @PostMapping("/register") public Result<?> register(@RequestParam(value="uname")String uname,@RequestParam(value="pwd")String pwd){ Boolean flag=userService.register(uname , pwd ); if(flag==true){ return Result.success().message("Register Success"); }else{ return Result.error().code(500).message("Username already exists!"); } } @GetMapping("/login") public Result<?> login(@RequestParam(value="uname")String uname,@RequestParam(value="pwd")String pwd){ UserEntity userInfo=this.userService.login(uname , pwd ); if(userInfo!=null && !"".equals(userInfo)){ return Result.success().data("userInfo",userInfo ).message("Login success"); }else{ return Result.error().code(401).message("Invalid credentials"); } } } ``` 以上便是整个项目的架构设计思路和技术选型依据,按照这样的模式可以快速搭建起一套完整的用户管理系统原型.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值