Springboot mybatis configuration

Time:2021-5-13

This paper introduces the configuration of mybatis and mybatis generator.

Dependent installation

<!-- Add MySQL plug-ins -- >
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
    <version>8.0.17</version>
</dependency>
<!-- Add mybatis plug-ins -- >
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.0</version>
</dependency>
<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.5</version>
</dependency>
<!-- Add the mybatis paging plug-in support, which can or can't be required -- >
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.0.0</version>
</dependency>

Add data source & mybatis configuration

Mybatis configuration document in springboot: http://mybatis.org/spring-boo…

Add the following content to application.properties:

#==================Mysql database=====================#
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/maven-test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#================== mybatis =====================#
#Map file path
mybatis.mapper-locations=classpath:mybatis/mapper/*Mapper.xml
#Specify mybatis build package
mybatis.type-aliases-package=com.chenglulu.mybatis.entity.*
#Specify the mybatis configuration file path
mybatis.config-location=classpath:mybatis/mybatis-config.xml

Mybatis configuration filemybatis-config.xmlas follows

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC
 "-//mybatis.org//DTD Config 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!--  Global mapper enable or disable caching. -- >
        <setting name="cacheEnabled" value="true"/>
        <!--  Globally enable or disable deferred loading -- >
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--  Allow or disallow multiple result sets to be returned from a single statement -- >
        <setting name="multipleResultSetsEnabled" value="true"/>
        <!--  Use column labels instead of column names -- >
        <setting name="useColumnLabel" value="true"/>
        <!--  Allow JDBC to support generated keys -- >
        <setting name="useGeneratedKeys" value="false"/>
        <!--  Configure the default actuator -- >
        <setting name="defaultExecutorType" value="SIMPLE"/>
        <!--  Set timeout -- >
        <setting name="defaultStatementTimeout" value="60"/>
        <!--  Setting hump logo -- >
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor" />
    </plugins>
<!--    <mappers>-->
<!--        <package name="classpath:mybatis/mapper/*Mapper.xml"></package>-->
<!--    </mappers>-->
</configuration>

Mybatis generator configuration

stayclasspath:mybatisNew under pathmybatis-generator.xmlDocuments.

<?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">
<!--  Configuration generator -- >
<generatorConfiguration>
    <!-- Classpathentry: jdbc driver for database. You can choose your own driver location -- >
    <!--    <classPathEntry  location="/Users/chenglulu/Documents/mysql-connector-java-8.0.17.jar"/>-->
    <!--  One database, one con ≤ text, defaultmodeltype = "flat" big data field, regardless of table -- > 
    <context id="MysqlTables" targetRuntime="MyBatis3" defaultModelType="flat">
        <!--  Automatically identify the database keywords. The default is false. If it is set to true, the database keywords will be identified according to the keyword list defined in sqlreservedwords; Generally, the default value is reserved. When the database keyword (Java keyword) is encountered, use columnoverride to override -- >
        <property name="autoDelimitKeywords" value="true"/>
        <!--  Encoding of generated java file -- >
        <property name="javaFileEncoding" value="utf-8"/>
        <!--  Beginingdelimiter and endingdelimiter: indicates the symbols used to mark database object names. For example, Oracle is double quotation marks, and MySQL is' back quotation marks' by default; -- >
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <!--  Format java code -- >
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
        <!--  Format XML code -- >
        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        <!--  Comment -- >
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <!--  Cancel comment -- >
            <property name="suppressDate" value="false"/> <!--  Generate comment generation timestamp -- >
        </commentGenerator>
        <!--  JDBC connection -- >
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
 connectionURL="jdbc:mysql://localhost:3306/maven-test?serverTimezone=UTC" userId="root"
 password="che021392">
            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>
        <!--  Type conversion -- >
        <javaTypeResolver>
            <!--  Use BigDecimal, false to automatically convert the following types (long, integer, short, etc.) -- >
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!--  Generate entity class address -- >
        <javaModelGenerator targetPackage="com.chenglulu.mybatis.entity" targetProject="src/main/java">
            <!--  Whether to allow subpackages, whether to use schema as the suffix of package -- >
            <property name="enableSubPackages" value="false"/>
            <!--  Do you want to add a constructor to modal
            <property name="constructorBased" value="true"/>
            <!--  Remove the space before and after the value returned from the database -- >
            <property name="trimStrings" value="true"/>
            <!--  To establish whether a modal object is immutable, that is, the generated modal object does not have a setter method, only a construction method -- >
            <property name="immutable" value="false"/>
        </javaModelGenerator>
        <!--  Generate map.xml file storage address -- >
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources/mybatis">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!--  Generate interface Dao -- >
        <javaClientGenerator targetPackage="com.chenglulu.mybatis.dao" targetProject="src/main/java" type="XMLMAPPER">
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>
        <!--  There can be multiple tables. Each table in the database can write a table. Tablename indicates the database table to be matched. You can also use% wildcard in the tablename attribute to match all database tables. Only the matching table will automatically generate a file. The corresponding configuration indicates whether to generate the corresponding interface -- >
        <table tableName="users"
                schema="root"
                domainObjectName="Users"
                enableCountByExample="true"
                enableUpdateByExample="true"
                enableDeleteByExample="true"
                enableSelectByExample="true"
                selectByExampleQueryId="true"
                enableSelectByPrimaryKey="true"
                enableUpdateByPrimaryKey="true"
                enableDeleteByPrimaryKey="true">
        </table>
    </context>
</generatorConfiguration>

Pom.xml configuration

  • Add resource packaging
<resources>
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>**/*.properties</include>
            <include>**/*.yml</include>
            <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
    </resource>
</resources>
  • Add mybatis generator configuration plug-in
<plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>${plugins.mybatis.generator.maven.version}</version>
                <configuration>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                    <configurationFile>src/main/resources/mybatis/mybatis-generator.xml</configurationFile>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.5</version>
                    </dependency>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>${dep.mysql.connector.java.version}</version>
                    </dependency>
                </dependencies>
            </plugin>

Start class add mapper interface scan

@SpringBootApplication
@MapperScan(basePackages = {"com.chenglulu.mybatis.dao"})
public class MySpringBootApplication {
    public static void main(String[] args){
        SpringApplication.run(MySpringBootApplication.class, args);
    }
}

Examples

Maven test database

First, create a new onemaven-testDatabase, and create a new users table, as shown in the following figure:

Springboot mybatis configuration

The structure of users table is as follows:

Springboot mybatis configuration

Generate mapper and Dao entity classes

implementmvn mybatis-generator:generate -eCommand:

  • Connect to the database, the database ismybatis-generator.xmlDatabase connections configured in
  • Generate entity class, corresponding tomybatis-generator.xmlintablesurface

The generated file is as follows:

  • Generate the usersmapper.xml file

Springboot mybatis configuration

  • Generate mapper and Dao entity classes

Springboot mybatis configuration

Service usage

package com.chenglulu.service.database;
import com.chenglulu.controller.users.domain.FindUsersParams;
import com.chenglulu.enums.UserDeleteEnum;
import com.chenglulu.enums.UserStatusEnum;
import com.chenglulu.mybatis.dao.UsersMapper;
import com.chenglulu.mybatis.entity.Users;
import com.chenglulu.mybatis.entity.UsersExample;
import com.chenglulu.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
@Slf4j
public class UsersDatabase {
    @Autowired(required=false)
    private UsersMapper usersMapper;
    /**
    *New user * @ param users users
    * @return boolean 
    */ 
    public Users insertUser(Users users){
        Date date = new Date();
        users.setId(CommonUtils.getUuid());
        users.setCreateTime(date);
        users.setUpdateTime(date);
        users.setStatus(UserStatusEnum.OK.getCode());
        users.setDelete(UserDeleteEnum.NORMAL.getCode());
        int insertResult = usersMapper.insertSelective(users);
        log.info("insertUser insertResult = {}", insertResult);
        if(insertResult == 1){
            return users;
        }
        return null;
    }
    /**
    *Query user list * @ param params findusers params
    * @return List<Users>
    */
    public List<Users> findUsers(FindUsersParams params){
        UsersExample example = new UsersExample();
        UsersExample.Criteria criteria = example.createCriteria();
        //They are arranged in descending order according to the creation time and in ascending order according to the ID; ASC ascending, desc descending, multiple conditions separated by commas
        example.setOrderByClause("create_time desc, id asc");
        if(StringUtils.isNotBlank(params.getUserId())){
            criteria.andIdEqualTo(params.getUserId());
        }
        //User name fuzzy query
        if(StringUtils.isNotBlank(params.getUsername())){
            criteria.andUserNameLike("%" + params.getUsername() + "%");
        }
        //Mobile number inquiry
        if(StringUtils.isNotBlank(params.getPhone())){
            criteria.andPhoneEqualTo(params.getPhone());
        }
        //Email fuzzy query
        if(StringUtils.isNotBlank(params.getEmail())){
            criteria.andEmailEqualTo("%" + params.getEmail() + "%");
        }
        //Delete status query
        if(params.getDelete() != null){
            criteria.andDeleteEqualTo(params.getDelete());
        }
        //Multi state filtering
        if(CollectionUtils.isNotEmpty(params.getStatusList())){
            criteria.andStatusIn(params.getStatusList());
        }
        List<Users> usersList = usersMapper.selectByExample(example);
        log.info("findUsers usersList = {}", usersList);
        return usersList;
    }
}