SpringBoot整合MySQL数据库和Mybatis

6,037 阅读5分钟

简介

SpringBoot 2.3.1.RELEASE版本,整合Mysql和Mybatis例子。

整合MySQL

pom中引入相关依赖包
<!--jdbc-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<!--mysql数据库驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
springboot的应用配置文件application.yml中添加数据库和数据库驱动配置
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/spring_practice?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
    username: spring-practice
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

整合Mybatis

pom引入依赖相关依赖
<!--mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>
springboot的应用配置文件application.yml中配置mybaits “*Mapper.xml”文件(sql都写到这些文件中)的位置
mybatis:
  mapper-locations: classpath:/mybatis/mapper/*.xml
在任意一个被@Configuration(@SpringBootApplication被@Configuration注解)注解的类上添加@MapperScan,指定mybaits的dao类所在的package
@SpringBootApplication(scanBasePackages = {"com.huang.*"})
@MapperScan({"com.huang.spring.practice"})
public class Application {

   public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
   }

}

整合mybatis-generator

使用mybatis来操作数据库的时,我们还需要创建dto、dao、*Mapper.xml文件。如果手动创建上述文件的话,那将会非常的麻烦!!!好在人民的智慧是无穷的,我们可以通过mybatis-generator插件来帮我们自动生成指定数据库表的dto、dao、*Mapper.xml。整合和使用mybaits-generator的步骤如下:

pom文件<build/>元素的<plugins/>下添加一个新的<plugin/>元素,来配置mybatis-generator插件的相关配置:
<plugin>
	<groupId>org.mybatis.generator</groupId>
	<artifactId>mybatis-generator-maven-plugin</artifactId>
	<version>1.4.0</version>
	<configuration>
		<!-- mybatis-generator用于自动生成代码的配置文件 -->
		<configurationFile>src/main/resources/mybatis/generatorConfig.xml</configurationFile>
		<verbose>true</verbose>
		<!-- 允许覆盖同名的文件 -->
		<overwrite>true</overwrite>
	</configuration>
    <!-- 配置JDBC驱动 -->
	<dependencies>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.20</version>
		</dependency>
	</dependencies>
</plugin>
在应用配置的数据库(spring_practice)中创建一张名字叫user的表:
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `age` smallint(6) NOT NULL,
  `city` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
创建配置文件src/main/resources/mybatis/generatorConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!--mybatis的代码生成器相关配置-->
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!-- 引入配置文件 -->

    <!-- 一个数据库一个context,context的子元素必须按照它给出的顺序
        property*,plugin*,commentGenerator?,jdbcConnection,javaTypeResolver?,
        javaModelGenerator,sqlMapGenerator?,javaClientGenerator?,table+
    -->
    <context id="myContext" targetRuntime="MyBatis3" defaultModelType="flat">

        <!-- 这个插件给生成的Java模型对象增加了equals和hashCode方法 -->
        <!--<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>-->

        <!-- 注释 -->
        <commentGenerator>
            <!-- 是否不生成注释 -->
            <property name="suppressAllComments" value="true"/>
            <!-- 不希望生成的注释中包含时间戳 -->
            <!--<property name="suppressDate" value="true"/>-->
            <!-- 添加 db 表中字段的注释,只有suppressAllComments为false时才生效-->
            <!--<property name="addRemarkComments" value="true"/>-->
        </commentGenerator>


        <!-- jdbc连接 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/spring_practice?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=GMT%2B8"
                        userId="spring-practice"
                        password="123456">
            <!--高版本的 mysql-connector-java 需要设置 nullCatalogMeansCurrent=true-->
            <property name="nullCatalogMeansCurrent" value="true"/>
        </jdbcConnection>

        <!-- 类型转换 -->
        <javaTypeResolver>
            <!--是否使用bigDecimal,默认false。
                false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer
                true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal-->
            <property name="forceBigDecimals" value="true"/>
            <!--默认false
                false,将所有 JDBC 的时间类型解析为 java.util.Date
                true,将 JDBC 的时间类型按如下规则解析
                    DATE                   -> java.time.LocalDate
                    TIME                   -> java.time.LocalTime
                    TIMESTAMP               -> java.time.LocalDateTime
                    TIME_WITH_TIMEZONE     -> java.time.OffsetTime
                    TIMESTAMP_WITH_TIMEZONE    -> java.time.OffsetDateTime
                -->
            <!--<property name="useJSR310Types" value="false"/>-->
        </javaTypeResolver>

        <!-- 生成实体类地址 -->
        <javaModelGenerator targetPackage="com.huang.spring.practice.user.dto" targetProject="src/main/java">
            <!-- 是否让 schema 作为包的后缀,默认为false -->
            <!--<property name="enableSubPackages" value="false"/>-->
            <!-- 是否针对string类型的字段在set方法中进行修剪,默认false -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- 生成Mapper.xml文件 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources/mybatis/mapper">
            <!--<property name="enableSubPackages" value="false"/>-->
        </sqlMapGenerator>

        <!-- 生成 XxxMapper.java 接口-->
        <javaClientGenerator targetPackage="com.huang.spring.practice.user.dao" targetProject="src/main/java" type="XMLMAPPER">
            <!--<property name="enableSubPackages" value="false"/>-->
        </javaClientGenerator>

        <!-- schema为数据库名,oracle需要配置,mysql不需要配置。
             tableName为对应的数据库表名
             domainObjectName 是要生成的实体类名(可以不指定,默认按帕斯卡命名法将表名转换成类名)
             enableXXXByExample 默认为 true, 为 true 会生成一个对应Example帮助类,帮助你进行条件查询,不想要可以设为false
             -->
        <!-- 给我们刚刚创建的user表自动生成dto、dao、mapper.xml-->
        <table schema="" tableName="user" domainObjectName="User"
               enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false" selectByExampleQueryId="false">
            <!--是否使用实际列名,默认为false-->
            <!--<property name="useActualColumnNames" value="false" />-->
        </table>
    </context>
</generatorConfiguration>
在项目根目录下执行mybatis-generator插件,根据generatorConfig.xml中的配置生成文件
mvn mybatis-generator:generate
执行成功
D:\JAVA\GIT\spring-practice>mvn mybatis-generator:generate
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building spring.practice 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- mybatis-generator-maven-plugin:1.4.0:generate (default-cli) @ spring.practice ---
[INFO] Connecting to the Database
[INFO] Introspecting table user
[INFO] Generating Record class for table user
[INFO] Generating Mapper Interface for table user
[INFO] Generating SQL Map for table user
[INFO] Saving file UserMapper.xml
[INFO] Saving file User.java
[INFO] Saving file UserMapper.java
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.010 s
[INFO] Finished at: 2020-07-12T12:06:26+08:00
[INFO] Final Memory: 21M/217M
[INFO] ------------------------------------------------------------------------

在项目中成功生成dto、dao、mapper.xml

image

测试通过myabtis查询数据

创建一个userController
package com.huang.spring.practice.user.controller;

import com.huang.spring.practice.user.dao.UserMapper;
import com.huang.spring.practice.user.dto.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * User controller层
 */
@RestController
@RequestMapping("/api/user/")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户id查询用户信息
     * 
     * @param id
     * @return
     */
    @GetMapping("/getUserInfo/{id}")
    public User getUserInfo(@PathVariable("id") Long id) {
        return userMapper.selectByPrimaryKey(id);
    }
}
往user表中插入一条数据
insert into user (name, age, city) values ('小明', '18', '深圳');

mysql> select * from user;
+----+--------+-----+--------+
| id | name   | age | city   |
+----+--------+-----+--------+
|  1 | 小明   |  18 | 深圳   |
+----+--------+-----+--------+
1 row in set (0.00 sec)
启动我们的SpringBoot应用,访问localhost:8080/api/user/getUserInfo/1

接口成功查询并返回我们之前插入的用户信息

image

项目代码地址

github.com/ambition080…

参考

MyBatis Generator Config 整体配置

MyBatis Generator Quick Start Guide

mybatis-generator自动生成代码插件使用详解

[基于 SpringBoot2.0+优雅整合 SpringBoot+Mybatis](segmentfault.com/a/119000001…)