I. Main points of this paper

Member services need to use the database, we use mysql here, ORM framework using Mybatis, following the code, will introduce SpringBoot how to integrate MyBatis, and automatically generate CRUD code. A complete catalog of articles in the series

  • Mybatis springboot integration

  • Mysql springboot integration

  • Mysql authorization

  • The MyBatis plug-in automatically generates the code

  • Junit 5 unit tests

Second, development environment

  • JDK 1.8
  • Maven 3.6.2
  • Lombok 1.18.18
  • Springboot 2.4.3
  • Mysql 5.6.46
  • junit 5
  • idea 2020

Install and configure mysql

1. Install mysql

“Build large distributed services (4) Docker build development environment install Mysql”

2, log in to mysql, authorize user access (if you are using mysql root, this step can be omitted), the development environment password can be simpler, % can be replaced with your machine network segment, such as ‘mmc_update’@’10.10.%’.

- authorization
grant all privileges on *.* to 'mmc_update'@The '%' identified by '123456';
-- Refresh permission
flush privileges;
Query all users in the MYSQL database
SELECT DISTINCT CONCAT('User: '''.user."' @ ',host,"'; ') AS query FROM mysql.user;

Copy the code

3. Create a library table

create database mmc;

use mmc;

drop table if exists Tbl_MemberInfo;

create table Tbl_MemberInfo
(
  `uid` bigint(11) NOT NULL auto_increment,
  `uname` varchar(20) NOT NULL,
  `usex` tinyint(4) DEFAULT NULL,
  `ubirth` datetime NOT NULL,
  `utel` char(11) DEFAULT NULL,
  `uaddr` varchar(255) DEFAULT NULL,
  `uphoto` longblob,
  `createTime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'Creation time',
  `updateTime` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Update Time',
  `state` tinyint(4) DEFAULT NULL,
  `delFlag` tinyint(4) DEFAULT '0' COMMENT 'Delete Status: 0 not deleted, 1 deleted'.PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Copy the code

4. Integrate mybatis plug-in to generate CRUD code

1. Modify pum. XML, add mysql, Mybatis dependency.

        <version.mybatis>1.3.0</version.mybatis>
        <version.mysql>5.1.48</version.mysql>

				<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${version.mysql}</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${version.mybatis}</version>
        </dependency>

Copy the code

2. Modify POM. XML and add mybatis plug-in.

            <! Mybatis code generator: support batch operation generation -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <configuration>
                    <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>${version.mysql}</version>
                        <scope>runtime</scope>
                    </dependency>
                    <dependency>
                        <groupId>com.itfsw</groupId>
                        <artifactId>mybatis-generator-plugin</artifactId>
                        <version>1.3.8</version>
                    </dependency>
                </dependencies>
            </plugin>
Copy the code

Add generatorconfig. XML file to SRC /main/resources directory to generate CRUD code.


      
<! DOCTYPEgeneratorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>


    <context id="test" targetRuntime="MyBatis3" defaultModelType="flat">

        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"></plugin>
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"></plugin>


        <! -- Insert the plugin in batches -->
        <plugin type="com.itfsw.mybatis.generator.plugins.BatchInsertPlugin">
            <! -- If enabled, the official plugin can decide whether to insert this field according to whether the attribute is empty. AllowMultiQueries =true Multiple SQL submission operations need to be enabled. Therefore, this function is not recommended. Plugins are disabled by default -->
            <property name="allowMultiQueries" value="false"/>
        </plugin>
        <! Select * from 'Model' where 'Column' = 'Model';
        <plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
        <! -- Existing update plugin -->
        <plugin type="com.itfsw.mybatis.generator.plugins.UpsertPlugin">
            <! UpsertByExample, upsertByExampleSelective operation! AllowMultiQueries =true Multiple SQL submission operations need to be enabled. Therefore, this function is not recommended. Plugins are disabled by default -->
            <property name="allowMultiQueries" value="false"/>
            <! - open the batch function, support batchUpsert batchUpsertWithBLOBs, batchUpserSelective! None of these methods supports the IncrementsPlugin method! Plugins are disabled by default -->
            <property name="allowBatchUpsert" value="true"/>
        </plugin>

        <! To prevent generated code from having too many comments, add the following configuration control -->
        <commentGenerator >
            <! -- This element is used to remove the generated comment if the generated comment contains the generated date.
            <! -- if the date is generated, all attributes of the entity class will change even if a field is changed, which is not good for version control, so set to true -->
            <property name="suppressDate" value="true" />
            <! -- Whether to remove automatically generated comments true: yes: false: no -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>


        <! -- Database link URL, username, password -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="JDBC: mysql: / / 9.135. XXX. XXX: 3306 / MMC" userId="root" password="123456">
            <property name="useInformationSchema" value="true"/>
            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>

        <javaTypeResolver>
            <! -- This property is used to specify whether MyBatis Generator should force the use of java.math.BigDecimal for DECIMAL and NUMERIC fields, -->
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <javaModelGenerator targetPackage="com.mmc.lesson.member.model"
                            targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
<! -- <property name="trimStrings" value="true" />-->
        </javaModelGenerator>


        <! Generate mapping file XML package name and location -->
        <sqlMapGenerator targetPackage="mysqlMappers"
                         targetProject="src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <! The package name and location where the DAO was generated
        <javaClientGenerator type="XMLMAPPER"
                targetPackage="com.mmc.lesson.member.mapper"
                targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>


        <table schema="mmc" tableName="Tbl_MemberInfo" domainObjectName="TblMemberInfo"
               enableCountByExample="true" enableUpdateByExample="true"
               enableDeleteByExample="true" enableSelectByExample="true"
               selectByExampleQueryId="true">
            <! -- Because the table fields are humped, the attributes remain the same -->
            <property name="useActualColumnNames" value="true"/>

            <columnOverride column="usex" javaType="Integer"/>
            <columnOverride column="state" javaType="Integer"/>
            <columnOverride column="delFlag" javaType="Integer"/>
        </table>


    </context>

</generatorConfiguration>
Copy the code

4. Double-click to run the plug-in.

5. Effect.

5. Modify the project configuration

Add @mapperscan to the start class memberApplication. Java.

@MapperScan(basePackages = "com.mmc.lesson.member.mapper")
@SpringBootApplication
public class MemberApplication {

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

Add data source configuration in application-dev.properties.

logging.file.path=./logs

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=JDBC: mysql: / / 9.135. XXX. XXX: 3306 / MMC? useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQuer ies=true&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456

mybatis.mapper-locations=classpath:mysqlMappers/*.xml
Copy the code

3. Write MemberService.java.

@Service
public class MemberService {

    @Resource
    private TblMemberInfoMapper tblMemberInfoMapper;

    public TblMemberInfo save(TblMemberInfo member) {

        int affect = tblMemberInfoMapper.insert(member);

        returnmember; }}Copy the code

Six, run it

1. Write unit tests.

@Slf4j
@ActiveProfiles("dev")
@ExtendWith(SpringExtension.class)
@SpringBootTest
@Transactional
public class MemberServiceTest {

    @Resource
    private MemberService memberService;

    /** * add. */
    @Test
    public void testAdd(a) {

        TblMemberInfo member = new TblMemberInfo();
        member.setUname("zhangsan");
        member.setUsex(1);
        member.setUbirth(new Date());
        member.setUtel("888");
        member.setUaddr("Ling Xiao Dian");
        member.setState(0);
        member.setDelFlag(0);
        member.setUphoto(null);

        TblMemberInfo ret = memberService.save(member);

        Assertions.assertThat(ret).isNotNull();
        log.info("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --"); log.info(ret.getUname()); }}Copy the code

2. Effect.

[2021-02-25 12:03:41974.] [main] [DEBUG] [c.m.l.member.mapper.TblMemberInfoMapper.insert:? ]  - ==> Parameters:null, zhangsan(String), 1(Integer), 2021-02-25 12:03:41729.(Timestamp), 888(String), Ling Xiao Dian (String),null.null.0(Integer), 0(Integer), null
[2021-02-25 12:03:41990.] [main] [DEBUG] [c.m.l.member.mapper.TblMemberInfoMapper.insert:? ]  - <== Updates:1
[2021-02-25 12:03:41991.] [main] [DEBUG] [org.mybatis.spring.SqlSessionUtils:? ]  - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2d64c100]
[2021-02-25 12:03:42032.] [main] [INFO] [com.mmc.lesson.member.service.MemberServiceTest:? ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -2021-02-25 12:03:42032.] [main] [INFO] [com.mmc.lesson.member.service.MemberServiceTest:? ]  - zhangsanCopy the code

Seven, summary

A few simple steps will enable the project to integrate Mybatis and automatically generate CRUD code. In high concurrency and big data scenarios, automatically generated code is not applicable, so handwritten Mapper operation will be added in the project. In addition to mybatis official starter, you can also use Baomidou starter. Next article: SpringBoot Integration with Database Connection Pool Hikari

Add me to exchange learning!