Spring Boot quickly integrates TK Mybatis

Posted by diode on Tue, 18 Jan 2022 02:05:57 +0100

introduce

TKMybatis is a tool developed based on the Mybatis framework. It internally implements the basic data operation of a single table. It can complete the single table operation without writing any sql by simply inheriting the interface provided by TKMybatis.

Add dependency

Add TKMybatis dependency

<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.1.5</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

Add TKMybatis code generator plug-in

 <build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.6</version>
            <configuration>
                <configurationFile>
                    src/main/resources/generator/generatorConfig.xml
                </configurationFile>
                <overwrite>true</overwrite>
                <verbose>true</verbose>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>5.1.47</version>
                </dependency>
                <dependency>
                    <groupId>tk.mybatis</groupId>
                    <artifactId>mapper</artifactId>
                    <version>4.1.5</version>
                </dependency>
            </dependencies>
        </plugin>

    </plugins>

</build>

Generate code

Write Src / main / resources / generator / generatorconfig xml

<!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="generator/config.properties"/>

    <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
            <property name="caseSensitive" value="true"/>
            <property name="lombok" value="Getter,Setter,ToString"/>
        </plugin>

        <jdbcConnection driverClass="${jdbc.driverClass}"
                        connectionURL="${jdbc.url}"
                        userId="${jdbc.user}"
                        password="${jdbc.password}">
        </jdbcConnection>

        <javaModelGenerator targetPackage="${project.package}.entity"
                            targetProject="src/main/java"/>

        <sqlMapGenerator targetPackage="mapper"
                         targetProject="src/main/resources"/>

        <javaClientGenerator targetPackage="${project.package}.dao"
                             targetProject="src/main/java"
                             type="XMLMAPPER"/>

        <table tableName="${project.tableName}">
            <generatedKey column="id" sqlStatement="JDBC"/>
        </table>
    </context>
</generatorConfiguration>

Write Src / main / resources / generator / config properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/demo?autoReconnect=true&serverTimezone=Asia/Shanghai
jdbc.user= root
jdbc.password=root

#Package name
project.package=com.example.helloworld
#Table name
project.tableName=good

Data sheets involved

CREATE TABLE `good`  (
  `id` int(8) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `good_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'Trade name',
  `good_price` decimal(10, 2) NOT NULL COMMENT 'commodity price',
  `create_time` datetime NOT NULL COMMENT 'Creation time',
  `update_time` datetime NOT NULL COMMENT 'Update time',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = 'Commodity list' ROW_FORMAT = Dynamic;

After configuration, refresh maven, and generate code through mybatis generator - > mybatis generator: generate in Maven plug-in

Newly generated code, such as:

├─java
│  └─com
│      └─example
│          └─helloworld
│              │
│              ├─dao
│              │      GoodMapper.java
│              │
│              └─entity
│                      Good.java
│
└─resources
   │
   └─mapper
           GoodMapper.xml

GoodMapper

package com.example.helloworld.dao;

import com.example.helloworld.entity.Good;
import tk.mybatis.mapper.common.Mapper;

public interface GoodMapper extends Mapper<Good> {
}

Good

package com.example.helloworld.entity;

import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.*;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
@Table(name = "good")
public class Good {
    /**
     * id
     */
    @Id
    @GeneratedValue(generator = "JDBC")
    private Integer id;

    /**
     * Trade name
     */
    @Column(name = "good_name")
    private String goodName;

    /**
     * commodity price
     */
    @Column(name = "good_price")
    private BigDecimal goodPrice;

    /**
     * Creation time
     */
    @Column(name = "create_time")
    private Date createTime;

    /**
     * Update time
     */
    @Column(name = "update_time")
    private Date updateTime;
}

mapper/GoodMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.helloworld.dao.GoodMapper">
  <resultMap id="BaseResultMap" type="com.example.helloworld.entity.Good">
    <!--
      WARNING - @mbg.generated
    -->
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="good_name" jdbcType="VARCHAR" property="goodName" />
    <result column="good_price" jdbcType="DECIMAL" property="goodPrice" />
    <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
    <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
  </resultMap>
</mapper>

Add scan

Start the class to add @ MapperScan scan. Note that TK mybatis. spring. MapperScan under annotation package

import tk.mybatis.spring.annotation.MapperScan;

@MapperScan("com.example.helloworld.dao")
@SpringBootApplication
public class HelloworldApplication {
	...
}

Basic use

tkmapper basic method

methoddescribe
Object selectOne(Object record)Query a single field by entity. If it is not empty, it is a condition
List select(Object record)According to the entity query list, if the field is not empty, it is a condition
List selectAll()Query all
int selectCount(Object record)According to entity calculation, if the field is not empty, it is a condition
Object selectByPrimaryKey(Object key)Query by PK
boolean existsWithPrimaryKey(Object key)Determine whether to operate according to the primary key
int insert(Object record)newly added
int insertSelective(Object record)New non null field
int updateByPrimaryKey(Object record)Update values by primary key
int updateByPrimaryKeySelective(Object record)Update fields with non null values by primary key
int delete(Object record)Delete according to the entity. If the field is not empty, it is a condition
int deleteByPrimaryKey(Object key)Delete by primary key
List selectByExample(Object example)Query list by criteria
Object selectOneByExample(Object example)Query individual by criteria
int selectCountByExample(Object example)Count by condition
int deleteByExample(Object example)Delete by condition
int updateByExample(Object record,Object example)Update values by criteria
int updateByExampleSelective(Object record,Object example)Update fields with non null values by criteria
List selectByExampleAndRowBounds(Object example ,RowBounds row)
List selectByRowBounds(Object record,RowBounds row)

example instance method

Example is used to add conditions, which is equivalent to the part after where. Theoretically, any complex condition query of a single table can be completed with example.

methoddescribe
example.setOrderByClause("field name ASC");Add ascending sort conditions and DESC is descending
example.setDistinct(false)Remove duplicates. boolean type. true means to select non duplicate records.
example.and(Criteria criteria)Add criteria query criteria for example. The relationship is and
example.or(Criteria criteria)Add criteria query criteria for example, and the relationship is or
criteria.andIsNullAdd condition with null field
criteria.andIsNotNullAdd a condition where the field is not null
criteria.andEqualTo(value)Add field equal to value condition
criteria.andNotEqualTo(value)Add field not equal to value condition
criteria.andGreaterThan(value)Add xxx field greater than value condition
criteria.andGreaterThanOrEqualTo(value)Add the condition that xxx field is greater than or equal to value
criteria.andLessThan(value)Add the condition that xxx field is less than value
criteria.andLessThanOrEqualTo(value)Add the condition that xxx field is less than or equal to value
criteria.andIn(List<?>)Add field values in list <? > condition
criteria.andNotIn(List<?>)Added field value is not in list <? > condition
criteria.andLike("%"+value+"%")Add fuzzy query criteria with field value of value
criteria.andNotLike("%"+value+"%")Add fuzzy query criteria whose field value is not value
criteria.andBetween(value1,value2)Add a condition where the field value is between value1 and value2
criteria.andNotBetween(value1,value2)Add a condition where the field value is not between value1 and value2

Using criteria basic fields

Example example = new Example(Good.class);
Criteria criteria = example.createCriteria();
criteria.andEqualTo("id", id);
criteria.andNotEqualTo("good_name", "xxx");
List<Good> list = goodMapper.selectByExample(example);          

The basic criteria field is not used to simplify the operation, but the essence is criteria

Example example = new Example(Good.class);
example.and()
    .andEqualTo("id", id)
    .andNotEqualTo("good_name", "xxx");
List<Good> list = goodMapper.selectByExample(example);

Topics: Java Mybatis Spring Spring Boot