Introduction to the

SpringBoot 2.3.1.RELEASE, integrate Mysql and Mybatis examples.

Integration of the MySQL

Introduce dependency packages into POM
<! --jdbc-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<! Mysql database driver -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
Copy the code
Add the database and database driver configuration to the SpringBoot application configuration file 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
Copy the code

Integration of Mybatis

Pom introduces dependency dependent dependencies
<! --mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>
Copy the code
The mybaits “* mapper. XML” file (into which SQL is written) is configured in the SpringBoot application configuration file application.yml
mybatis:
  mapper-locations: classpath:/mybatis/mapper/*.xml
Copy the code
Add @Mapperscan to any class annotated by @Configuration(@SpringBootApplication annotated by @Configuration), specifying the package in which the DAO class of MyBaits resides
@SpringBootApplication(scanBasePackages = {"com.huang.*"})
@MapperScan({"com.huang.spring.practice"})
public class Application {

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

Integrated mybatis generator

When using Mybatis to operate the database, we also need to create DTO, DAO, * mapper. XML files. If you create the above file manually, it will be very troublesome!! Fortunately, the wisdom of the people is infinite, we can use mybatis-generator plug-in to help us automatically generate specified database table DTO, DAO, * mapper.xml. The steps for integrating and using mybaits-Generator are as follows:

Add a new <plugin/> element under <plugins/> to the POM file <build/> element to configure the mybatis -Generator plugin:
<plugin>
	<groupId>org.mybatis.generator</groupId>
	<artifactId>mybatis-generator-maven-plugin</artifactId>
	<version>1.4.0</version>
	<configuration>
		<! -- Mybatis -generator configuration file for automatic code generation
		<configurationFile>src/main/resources/mybatis/generatorConfig.xml</configurationFile>
		<verbose>true</verbose>
		<! Allow overwriting files with the same name
		<overwrite>true</overwrite>
	</configuration>
    <! -- Configure JDBC driver -->
	<dependencies>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.20</version>
		</dependency>
	</dependencies>
</plugin>
Copy the code
Create a table named user in the application configuration database (spring_practice) :
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;
Copy the code
Create a configuration file SRC/main/resources/mybatis generatorConfig. XML
<?xml version="1.0" encoding="UTF-8" ? >
<! Mybatis code generator configuration -->

      

<generatorConfiguration>
    <! -- Import configuration file -->

    <! A database has a context, and the children of the context must be in the order they are given. Property *,plugin*,commentGenerator? ,jdbcConnection,javaTypeResolver? , javaModelGenerator,sqlMapGenerator? ,javaClientGenerator? ,table+ -->
    <context id="myContext" targetRuntime="MyBatis3" defaultModelType="flat">

        <! -- This plugin adds equals and hashCode methods to generated Java model objects -->
        <! --<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>-->

        <! - comments -- >
        <commentGenerator>
            <! Do not generate comments -->
            <property name="suppressAllComments" value="true"/>
            <! -- Do not want generated comments to contain timestamps -->
            <! --<property name="suppressDate" value="true"/>-->
            <! Add comments for db table fields only when suppressAllComments is false -->
            <! --<property name="addRemarkComments" value="true"/>-->
        </commentGenerator>


        <! -- JDBC connection -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="JDBC: mysql: / / 127.0.0.1:3306 / spring_practice? useUnicode=true& characterEncoding=utf8& useSSL=false& serverTimezone=GMT%2B8"
                        userId="spring-practice"
                        password="123456">
            <! NullCatalogMeansCurrent =true nullCatalogMeansCurrent=true
            <property name="nullCatalogMeansCurrent" value="true"/>
        </jdbcConnection>

        <! -- Type conversion -->
        <javaTypeResolver>
            <! -- Whether to use bigDecimal, default is false. False, parse JDBC DECIMAL and NUMERIC types to Integer true, and parse JDBC DECIMAL and NUMERIC types to java.math.bigDecimal -->
            <property name="forceBigDecimals" value="true"/>
            <! -- Default false false, parse all JDBC time types to java.util.Date true, 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>

        <! Create entity class address -->
        <javaModelGenerator targetPackage="com.huang.spring.practice.user.dto" targetProject="src/main/java">
            <! -- Whether to use schema as package suffix, default is false -->
            <! --<property name="enableSubPackages" value="false"/>-->
            <! -- Whether to trim a string field in set (default: false) -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <! Create mapper.xml file -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources/mybatis/mapper">
            <! --<property name="enableSubPackages" value="false"/>-->
        </sqlMapGenerator>

        <! Create xxxmapper.java interface -->
        <javaClientGenerator targetPackage="com.huang.spring.practice.user.dao" targetProject="src/main/java" type="XMLMAPPER">
            <! --<property name="enableSubPackages" value="false"/>-->
        </javaClientGenerator>

        <! -- Schema indicates the name of the database. Oracle needs to be configured, but mysql does not. TableName specifies the name of the corresponding database table. DomainObjectName specifies the name of the entity class to be generated. By default, the PASCAL naming method converts the tableName to the class name. If this is true, an Example helper class will be generated to help you query the condition. If this is not true, you can set it to false.
        <! Create dTO, DAO, mapper.xml for user;
        <table schema="" tableName="user" domainObjectName="User"
               enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false" selectByExampleQueryId="false">
            <! -- Whether to use actual column names, default is false-->
            <! --<property name="useActualColumnNames" value="false" />-->
        </table>
    </context>
</generatorConfiguration>
Copy the code
Execute the mybatis -Generator plug-in in the project root directory and generate the file according to the configuration in Generatorconfig.xml
mvn mybatis-generator:generate
Copy the code
Execute successfully
D:\JAVA\GIT\spring-practice>mvn mybatis-generator:generate
[INFO] Scanning forprojects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building spring.practice 0.0.1 - the 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 classfor table user
[INFO] Generating Mapper Interface for table user
[INFO] Generating SQL Map fortable 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] ------------------------------------------------------------------------Copy the code
Dto, DAO, mapper.xml were successfully generated in the project

The test queries data through Myabtis

Create a 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 layer */
@RestController
@RequestMapping("/api/user/")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    /** * Query user information based on user ID **@param id
     * @return* /
    @GetMapping("/getUserInfo/{id}")
    public User getUserInfo(@PathVariable("id") Long id) {
        returnuserMapper.selectByPrimaryKey(id); }}Copy the code
Insert a row into the user table
Insert into user (name, age, city) values (' xiaowei ', '18', 'shenzhen '); mysql> select * from user; + - + -- -- -- -- -- -- -- -- + + -- -- -- -- -- -- -- -- -- -- -- -- -- + | | id name | age | city | + - + -- -- -- -- -- -- -- -- + + -- -- -- -- -- -- -- -- -- -- -- -- -- + | 1 | xiaoming | | | shenzhen 18 + - + -- -- -- -- -- -- -- -- + + -- -- -- -- -- -- -- -- -- -- -- -- -- + 1 row in the set (0.00 SEC)Copy the code
Start our SpringBoot application, access localhost: 8080 / API/user/getUserInfo / 1

The interface successfully queried and returned the user information we inserted earlier

Project code address

Github.com/ambition080…

reference

MyBatis Generator Config overall configuration

MyBatis Generator Quick Start Guide

Mybatis – Generator automatic generation code plug-in use details

[based on SpringBoot2.0 + elegant integration SpringBoot + Mybatis] (segmentfault.com/a/119000001…).