使用mybatis-generator-plugin自动生成代码整合SpringBoot+MyBatis

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: 使用mybatis-generator-plugin自动生成代码整合SpringBoot+MyBatis

文章目录


1、创建SpringBoot工程

本示例项目代码下载地址:

https://download.csdn.net/download/mouday/12662948

使用Spring Initializer创建SpringBoot工程,只用如下依赖

Web
MySQL
MyBatis

2、项目结构

25.2.png


$ tree
.
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── mouday
        │           └── demo
        │               ├── Application.java
        │               ├── controller
        │               │   └── PersonController.java
        │               ├── mapper
        │               │   ├── PersonMapper.java
        │               │   └── PersonMapper.xml
        │               ├── pojo
        │               │   └── Person.java
        │               └── service
        │                   ├── PersonService.java
        │                   └── impl
        │                       └── PersonServiceImpl.java
        └── resources
            ├── application.yml
            ├── generator
            │   └── generatorConfig.xml
            ├── sql
            │   └── person.sql
            ├── static
            └── templates

3、配置文件

3个配置文件和1个建表语句文件

pom.xml               # 项目依赖 
application.yml       # 项目配置 
generatorConfig.xml   # 自动代码生成配置 
person.sql            # 建表语句

pom.xml

<?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.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.mouday</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <!-- 数据库连接 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--使用durid连接池的依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <!--编译src/main/java目录下的xml文件-->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- 自动生成代码插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <!-- 依赖 -->
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>8.0.20</version>
                    </dependency>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.5</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

application.yml

# 设置端口
server:
  port: 8080
# 设置数据源
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/data
    username: root
    password: 123456
    # 连接池类型
    type: com.alibaba.druid.pool.DruidDataSource
    # 驱动
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 连接池配置
    druid:
      # 最小数
      min-idle: 5
      # 最大数
      max-active: 20
      # 初始大小
      initial-size: 5
      # 配置获取连接等待超时时间
      max-wait: 6000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      time-between-eviction-runs-millis: 60000
      # 配置一个连接在池中最小生存时间  单位为毫秒
      min-evictable-idle-time-millis: 300000
      validation-query: SELECT 1 FROM DUAL
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      # 打开 PSCache,并且指定每个连接上PSCache的大小
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,wall用于防火墙
      filters: stat,wall
# 配置mybatis
mybatis:
#  mapper-locations: classpath:mappers/*.xml
  # 全局的映射,不用在xml文件写实体类的全路径
#  type-aliases-package: com.mouday.demo.pojo
  configuration:
    # 开启驼峰映射
    map-underscore-to-camel-case: true

generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
    <context id="default" targetRuntime="MyBatis3">
        <!--创建class时,对注释进行控制-->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!-- jdbc的数据库连接 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/data"
                        userId="root"
                        password="123456">
        </jdbcConnection>
        <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制 -->
        <javaTypeResolver>
            <!-- 是否使用BigDecimals,false可自动转化以下类型(Long Integer Short等) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- Model模型生成器-->
        <javaModelGenerator targetPackage="com.mouday.demo.pojo"
                            targetProject="src/main/java">
            <!--是否允许子包,即targetPackage.schemaName.tableName-->
            <property name="enableSubPackages" value="true"/>
            <!-- 是否对类CHAR类型的列的数据进行trim操作 -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- Mapper映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="com.mouday.demo.mapper"
                         targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 客户端代码-->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.mouday.demo.mapper"
                             targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
        <table tableName="person"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>

person.sql

CREATE TABLE `person` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL
)

4、执行代码生成

$ mvn mybatis-generator:generate

生成3个文件

Person.java                       # model
PersonMapper.java                 # mapper接口
PersonMapper.xml                  # sql映射

Person.java

package com.mouday.demo.pojo;
public class Person {
    private Integer id;
    private String name;
    private Integer age;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
}

PersonMapper.java

package com.mouday.demo.mapper;
import com.mouday.demo.pojo.Person;
public interface PersonMapper {
    int deleteByPrimaryKey(Integer id);
    int insert(Person record);
    int insertSelective(Person record);
    Person selectByPrimaryKey(Integer id);
    int updateByPrimaryKeySelective(Person record);
    int updateByPrimaryKey(Person record);
}

PersonMapper.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.mouday.demo.mapper.PersonMapper">
  <resultMap id="BaseResultMap" type="com.mouday.demo.pojo.Person">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="age" jdbcType="INTEGER" property="age" />
  </resultMap>
  <sql id="Base_Column_List">
    id, name, age
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from person
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from person
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.mouday.demo.pojo.Person">
    insert into person (id, name, age
      )
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.mouday.demo.pojo.Person">
    insert into person
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="name != null">
        name,
      </if>
      <if test="age != null">
        age,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        #{age,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.mouday.demo.pojo.Person">
    update person
    <set>
      <if test="name != null">
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        age = #{age,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.mouday.demo.pojo.Person">
    update person
    set name = #{name,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

5、Service和Controller

对外服务接口

PersonService.java       # 接口
PersonServiceImpl.java   # 实现
PersonController.java    # 控制器

PersonService.java

package com.mouday.demo.service;
import com.mouday.demo.pojo.Person;
public interface PersonService {
    int deleteByPrimaryKey(Integer id);
    int insert(Person record);
    int insertSelective(Person record);
    Person selectByPrimaryKey(Integer id);
    int updateByPrimaryKeySelective(Person record);
    int updateByPrimaryKey(Person record);
}

PersonServiceImpl.java

package com.mouday.demo.service.impl;
import com.mouday.demo.mapper.PersonMapper;
import com.mouday.demo.pojo.Person;
import com.mouday.demo.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PersonServiceImpl implements PersonService {
    @Autowired
    private PersonMapper personMapper;
    @Override
    public int deleteByPrimaryKey(Integer id) {
        return personMapper.deleteByPrimaryKey(id);
    }
    @Override
    public int insert(Person record) {
        return personMapper.insert(record);
    }
    @Override
    public int insertSelective(Person record) {
        return personMapper.insertSelective(record);
    }
    @Override
    public Person selectByPrimaryKey(Integer id) {
        return personMapper.selectByPrimaryKey(id);
    }
    @Override
    public int updateByPrimaryKeySelective(Person record) {
        return personMapper.updateByPrimaryKeySelective(record);
    }
    @Override
    public int updateByPrimaryKey(Person record) {
        return personMapper.updateByPrimaryKey(record);
    }
}

PersonController.java

package com.mouday.demo.controller;
import com.mouday.demo.pojo.Person;
import com.mouday.demo.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/person")
public class PersonController {
    @Autowired
    private PersonService personService;
    @GetMapping("/selectByPrimaryKey")
    public Person selectByPrimaryKey(Integer id){
        return personService.selectByPrimaryKey(id);
    }
}

6、运行启动

package com.mouday.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
@MapperScan("com.mouday.demo.mapper") // 指定mapper扫描包
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    @GetMapping("/")
    public String index(){
        return "hello";
    }
}

请求和返回结果

GET http://localhost:8080/person/selectByPrimaryKey?id=1
{
  id: 1,
  name: "刘禅",
  age: 26
}

参考

SpringBoot集成MyBatis及使用mybatis-generator-plugin生成代码(完美,步骤巨详细)

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
22天前
|
Java 关系型数据库 数据库连接
Mybatis+MySQL动态分页查询数据经典案例(含代码以及测试)
Mybatis+MySQL动态分页查询数据经典案例(含代码以及测试)
22 1
|
26天前
|
XML Java 数据库连接
mybatis环境搭建步骤(含配置文件代码)
mybatis环境搭建步骤(含配置文件代码)
14 1
|
27天前
|
前端开发 Java 关系型数据库
SpringBoot+MyBatis 天猫商城项目
SpringBoot+MyBatis 天猫商城项目
47 1
|
26天前
|
SQL Java 数据库连接
springboot中配置mybatis别名该怎么写?
springboot中配置mybatis别名该怎么写?
19 0
|
26天前
|
SQL JavaScript Java
springboot+springm vc+mybatis实现增删改查案例!
springboot+springm vc+mybatis实现增删改查案例!
22 0
|
7天前
|
SQL Java 数据库连接
【mybatis】第一篇,Springboot中使用插件PageHelper不生效解决方案
【mybatis】第一篇,Springboot中使用插件PageHelper不生效解决方案
|
19天前
|
JavaScript Java 关系型数据库
SpringBoot + Mybatis + Vue的代码生成器
SpringBoot + Mybatis + Vue的代码生成器
31 2
|
26天前
|
Java 关系型数据库 MySQL
springboot+mybatis-plus实例demo
springboot+mybatis-plus实例demo
28 0
|
28天前
|
SQL Java 关系型数据库
MyBatisPlus学习笔记(SpringBoot版)
MyBatisPlus学习笔记(SpringBoot版)
98 0
|
28天前
|
关系型数据库 Java 数据库连接
如何利用Mybatis-Plus自动生成代码(超详细注解)
如何利用Mybatis-Plus自动生成代码(超详细注解)
25 1