0120 springboot Mybatis integration and code generator

In the daily development, shelf data persistence technology used most frequently there are three that spring-jdbc, spring-jpa, spring-mybatis. For more information please see my previous article 3 shelves spring operation of the database  .

spring-jdbc package is relatively small, it is necessary splicing sql code, not suitable for large-scale enterprise-level development.
slightly more spring-jpa package, suitable for the development of the background class management system can reduce a lot of work is repeated.

However, in the current Internet environment, spring-mybatis not only brings convenience to develop, but also without losing flexibility, especially for high-performance requirements, flexibility to change the scene. This article generally look at the development of auto-generated based on the configuration of springboot of points mybatis and code-based maven plugin.

hello, springboot mybatis integration and code generator!

springboot integrated Mybatis

springboot integrated Mybatis have a lot of articles, but do not look at someone else's point of view, do you think starting from 0 configuration, which steps should have it?

I think roughly divided into the following points:

1. dependence introduction, database driven, the MyBatis Starter;

Configuration database connection information, the connection pool information;

1. Configure mybatis core configuration information; entity location such as location, type of actuator, the XML;

1. Configure springboot of Mybatis notes, mostly open support, then the mapper address;

1. Start a successful test: can be placed inside to do a health check;

springboot integrated Mybatis key steps: after the integration is completed, the rest of the code generator is used to generate a good regular entity, xml, mapper, example these basic code, and then combined service logic, to add a new method code mapper;

Here together with me step by step integration springboot:

1 dependent

Create a project using the spring initializr, dependent on the introduction of the following:

image.png

Dependent as follows:

Data source configuration 2

Springboot default data source data source comes hikari;
configuration is as follows:

Database connection information

spring.datasource.url=jdbc:mysql://10.19.174.11:3306/demo_datasource
spring.datasource.username=lxdev
spring.datasource.password=db@LX4devtmp123
spring.datasource.type=com.zaxxer.hikari.HikariDataSource复制代码

Data connection pool configuration information

spring.datasource.hikari.pool-name=demo_mybatis_and_plugin_pool
spring.datasource.hikari.maximum-pool-size=5
spring.datasource.hikari.allow-pool-suspension=false复制代码


3 mybatis configuration

mybatis mainly arranged mapper-locations, type-alias-package, and the hump correspondence relationship, and other types of actuators;

#mybatis配置
mybatis.mapper-locations=classpath:com/springbootpractice/demo/mybatis/plugin/dao/xml/*.xml
mybatis.type-aliases-package=com.springbootpractice.demo.mybatis.plugin.dao.entity
mybatis.executor-type=reuse
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.cache-enabled=true
mybatis.lazy-initialization=true复制代码

Inlet 4 arranged @MapperScan

Package location to tell the application where the mapper interfaces, and identifying comment.

package com.springbootpractice.demo.mybatis.plugin;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Repository;

@SpringBootApplication
@MapperScan(annotationClass = Repository.class,
        basePackages = "com.springbootpractice.demo.mybatis.plugin.dao.mapper")
public class DemoMybatisAndPluginApplication {

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

}复制代码

5 database health checks

First configure the actuator, open health endpoints;

#ops配置
management.endpoints.web.exposure.include=*
management.endpoints.enabled-by-default=false
management.endpoint.health.enabled=true
management.endpoint.health.show-details=always复制代码

Check the connection state database 6

Initiator, curl http://localhost:8080/actuator/health/db  you can check the connection status of the database, a normal return the following results:

{
status: "UP",
details:- {
database: "MySQL",
result: 1,
validationQuery: "/* ping */ SELECT 1"
}
}复制代码

So far, springboot step integration mybatis completed. But some template code, you need to remember? It should be very painful memories. So, we should configure the look mybatis code generation plug-in to generate a good number of commonly used code, and then add some of their own persistence mapper method on the basis of the generated code provided with the service layer calls.

Code generator

Code generator, mybatis official website described. Configuration is divided into plug-in configuration and generation configuration. This paper is performed by a conventional code generation maven plugin.

Code Generation Plug official website provides introduction

Plug-in configuration

Maven plug mainly used, configured as follows: the primary need configured to generate position code profile;

<plugin>
       <groupId>org.mybatis.generator</groupId>
       <artifactId>mybatis-generator-maven-plugin</artifactId>
       <version>1.3.7</version>
       <configuration>
           <configurationFile>${project.basedir}/src/main/resources/generateConfig.xml</configurationFile>
           <verbose>false</verbose>
           <overwrite>true</overwrite>
       </configuration>
       <dependencies>
           <dependency>
               <groupId>mysql</groupId>
               <artifactId>mysql-connector-java</artifactId>
               <version>5.1.31</version>
           </dependency>
           <dependency>
               <groupId>com.itfsw</groupId>
               <artifactId>mybatis-generator-plugin</artifactId>
               <version>1.3.8</version>
           </dependency>
       </dependencies>
</plugin>复制代码

Configuration points are as follows:

Generating code configuration

Several main configuration code generated position information mapper, entity, example, xml, and database connections. And then configure a few I think very useful reinforcing plug.

Configuration code as follows

<?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>
    <properties resource="jdbc.properties"></properties>
    <context defaultModelType="flat" id="Mysql" targetRuntime="MyBatis3">
        <property name="endingDelimiter" value="`"/>
        <property name="beginningDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>
        <property name="autoDelimitKeywords" value="true"/>
        <!-- 自定义注释插件 -->
        <plugin type="com.itfsw.mybatis.generator.plugins.CommentPlugin">
            <!-- 自定义模板路径 -->
            <property name="template" value="src/main/resources/comment.ftl"/>
        </plugin>
        <plugin type="com.itfsw.mybatis.generator.plugins.LombokPlugin">
            <!-- @Data 默认开启,同时插件会对子类自动附加@EqualsAndHashCode(callSuper = true),@ToString(callSuper = true) -->
            <property name="@Data" value="true"/>
            <!-- @Builder 必须在 Lombok 版本 >= 1.18.2 的情况下开启,对存在继承关系的类自动替换成@SuperBuilder -->
            <property name="@Builder" value="true"/>
            <!-- @NoArgsConstructor 和 @AllArgsConstructor 使用规则和Lombok一致 -->
            <property name="@AllArgsConstructor" value="true"/>
            <property name="@NoArgsConstructor" value="true"/>
            <!-- @Getter、@Setter、@Accessors 等使用规则参见官方文档 -->
            <property name="@Accessors(chain = true)" value="false"/>
            <!-- 临时解决IDEA工具对@SuperBuilder的不支持问题,开启后(默认未开启)插件在遇到@SuperBuilder注解时会调用ModelBuilderPlugin来生成相应的builder代码 -->
            <property name="supportSuperBuilderForIdea" value="false"/>
        </plugin>
        <!-- Mapper注解插件 -->
        <plugin type="com.itfsw.mybatis.generator.plugins.MapperAnnotationPlugin">
            <!-- @Mapper 默认开启 -->
            <property name="@Mapper" value="false"/>
            <!-- @Repository 默认关闭,开启后解决IDEA工具@Autowired报错 -->
            <property name="@Repository" value="true"/>
        </plugin>
        <!-- MySQL分页插件 -->
        <plugin type="com.itfsw.mybatis.generator.plugins.LimitPlugin">
            <!-- 通过配置startPage影响Example中的page方法开始分页的页码,默认分页从0开始 -->
            <property name="startPage" value="1"/>
        </plugin>
        <plugin type="com.itfsw.mybatis.generator.plugins.ExampleTargetPlugin">
            <!-- 修改Example类生成到目标包下 -->
            <property name="targetPackage" value="${code.base.package}.example"/>
        </plugin>
        <!-- 状态枚举生成插件 -->
        <plugin type="com.itfsw.mybatis.generator.plugins.EnumTypeStatusPlugin">
            <!-- 是否开启自动扫描根据约定注释格式生成枚举,默认true  注释[success(0):成功, fail(1):失败]-->
            <property name="autoScan" value="true"/>
        </plugin>
        <!-- 逻辑删除插件 -->
        <plugin type="com.itfsw.mybatis.generator.plugins.LogicalDeletePlugin">
            <!-- 这里配置的是全局逻辑删除列和逻辑删除值,当然在table中配置的值会覆盖该全局配置 -->
            <!-- 逻辑删除列类型只能为数字、字符串或者布尔类型 -->
            <property name="logicalDeleteColumn" value="deleted"/>
            <!-- 逻辑删除-已删除值 -->
            <property name="logicalDeleteValue" value="1"/>
            <!-- 逻辑删除-未删除值 -->
            <property name="logicalUnDeleteValue" value="0"/>
            <!-- 是否生成逻辑删除常量(只有开启时 logicalDeleteConstName、logicalUnDeleteConstName 才生效) -->
            <property name="enableLogicalDeleteConst" value="true"/>
            <!-- 逻辑删除常量名称,不配置默认为 IS_DELETED -->
            <property name="logicalDeleteConstName" value="IS_DELETED"/>
            <!-- 逻辑删除常量(未删除)名称,不配置默认为 NOT_DELETED -->
            <property name="logicalUnDeleteConstName" value="NOT_DELETED"/>
        </plugin>
        <jdbcConnection connectionURL="${spring.datasource.url}" driverClass="${spring.datasource.driver-class-name}"
                        password="${spring.datasource.password}" userId="${spring.datasource.username}"/>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="true"/>
            <property name="useJSR310Types" value="true"/>
        </javaTypeResolver>
        <javaModelGenerator targetPackage="${code.base.package}.entity"
                            targetProject="src/main/java">
            <property name="trimStrings" value="true"/>
            <property name="enableSubPackages" value="true"/>
        </javaModelGenerator>
        <sqlMapGenerator targetPackage="${code.base.package}.xml" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <javaClientGenerator targetPackage="${code.base.package}.mapper"
                             targetProject="src/main/java" type="XMLMAPPER">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <table domainObjectName="UserLoginExtEntity" tableName="user_login_ext"
               enableDeleteByExample="false" enableDeleteByPrimaryKey="false">
            <generatedKey column="id" identity="true" sqlStatement="MySql"/>
        </table>
    </context>
</generatorConfiguration>
复制代码

In addition, the two also externalize the configuration information.
jdbc.properties: primary connection information configuration data, the name of the parent package;

spring.datasource.url=jdbc:mysql://10.19.174.11:3306/demo_datasource
spring.datasource.username=lxdev
spring.datasource.password=db@LX4devtmp123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
code.base.package=com.springbootpractice.demo.mybatis.plugin.dao复制代码

comment.ftl configured format generated comment;

<?xml version="1.0" encoding="UTF-8"?>
<template>
    <comment ID="addJavaFileComment"></comment>
    <comment ID="addComment"></comment>
    <comment ID="addRootComment"></comment>
    <comment ID="addFieldComment"><![CDATA[
        <#if introspectedColumn??>
            /**
            <#if introspectedColumn.remarks?? && introspectedColumn.remarks != ''>
                <#list introspectedColumn.remarks?split("\n") as remark>
* ${remark}  对应数据库表字段: ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName}
                </#list>
            </#if>
*/
        <#else>
        </#if>
        ]]></comment>
    <comment ID="addModelClassComment"><![CDATA[
/**
* @author: carter
* 对应数据库表: ${introspectedTable.fullyQualifiedTable}
*/
        ]]></comment>
    <comment ID="addClassComment"></comment>
    <comment ID="addEnumComment"></comment>
    <comment ID="addInterfaceComment"></comment>
    <comment ID="addGetterComment"></comment>
    <comment ID="addSetterComment"></comment>
    <comment ID="addGeneralMethodComment"></comment>
</template>
复制代码

**

summary

By this article you will learn the following:

  1. 0 mybatis integrated foundation for your springboot application;
  2. Mybatis plug configuration code generator and for generating the code, improve work efficiency;

I get the code point!

After springboot integrated mybatis, configure code generation plug-in, you can have a lot of time to focus on developing business logic, rapid completion of development work, have a lot of time off work to go back with the baby. The demo can be used in a production environment, through product testing. Ease of use, do not mention it away!

Whether you have no gain, or to send beautiful, most recently in chase drama, guess who this beauty is? Chicken fairy for you.
image.png

The original is not easy, please indicate the source.

Guess you like

Origin juejin.im/post/5e257296e51d4530e60e4725