springboot integrates tkmybatis and uses

As we all know with mybatis, there is a very unfriendly problem in using mybatis orm framework, that is, every operation of a single table needs to write an xml file by hand. Although the problem can be solved by generating xml and entity classes with tools, it can be solved by modifying a table field in the second development. When it comes to generating xml files, it's not realistic. The recent discovery of tkmybatis is a very good solution to this problem. Share it with you here.

  • Framework configuration

The package you need to refer to here

 <!--mybatis Operating database is related-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!--Connect mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--Using Alibaba druid Data Source, Favorable for Monitoring sql Implementation-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!--currency mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>
        <!--Add to lombok Support can save writing get and set Method-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
            <optional>true</optional>
        </dependency>
        <!--Use fastjson To operate json data-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.31</version>
        </dependency>

        <!--spring boot web Aspect support-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.4.RELEASE</version>
        </dependency>

Data source configuration

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

Table structure statement

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `user_phone` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `user_name_index`(`user_name`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'evan', '26');
INSERT INTO `user` VALUES (2, 'evan11', '26');

  • Class Configuration Method
    Entity class method
    Note that this is a reference to the lombok framework, you can omit writing get, set and other methods, where idea needs to add lombok plug-ins, if there is an error. (If you have obsessive-compulsive disorder) Actually, the code can still run.
@Data
@Table(name="user")
public class UserModel  {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY,generator = "JDBC")
    private Integer id;
    @Column
    private String userName;
    @Column
    private String userPhone;

}

Where @Table is the table name of the data table, @Column is the column name, @Id is the primary key, it should be noted that @Id annotation can not be multiple, @Transient is the redundant field, does not correspond to any field in the database.
Note the case of multiple data sources: then the @Table annotation can be written as "{database name}. {schema name}. {table name}", such as @Table(name= "db.dbo.tableName").

  • Service class
    Here we mainly implement the five Mapper methods inherited from the BaseMapper above.
    There are many methods in tk.mybatis.mapper.common.BaseMapper, which need to be inherited and implemented:
 /**
	 * Save an entity, and null attributes will also be saved
	 * 
	 * @param record
	 * @return
	 */
	int insert(T record);
 
	/**
	 * Save an entity, null attribute will not be saved
	 * 
	 * @param record
	 * @return
	 */
	int insertSelective(T record);
 
	/**
	 * Delete according to entity attribute as condition, and use equal sign for query condition.
	 */
	int delete(T record);
 
	/**
	 * Update values of attributes that are not null based on primary keys
	 */
	int updateByPrimaryKeySelective(T record);
 
	/**
	 * Query according to the attribute value in the entity, and use the equal sign for the query condition.
	 */
	List<T> select(T record);
 
	/**
	 * By querying all the results, the select(null) method achieves the same effect.
	 */
	List<T> selectAll();
 
	/**
	 * Queries based on attributes in entities can only have one return value, with multiple results throwing exceptions, and query conditions using an equal sign
	 */
	T selectOne(T record);
 
	/**
	 * According to the total number of attribute queries in the entity, the query condition uses the equal sign.
	 */
	int selectCount(T record);

The methods in MySqlMapper are as follows:

/**
	 * Batch insertion, database supporting batch insertion can be used, such as MySQL,H2, etc. In addition, the interface restricts entities to contain `id'attributes and must be self-added.
	 */
	public int insertList(List<T> recordList);
 
	/**
	 * Insert data to restrict entities to include `id'attributes and must be self-incremental. The primary key policy for entity configuration is invalid
	 */
	public int insertUseGeneratedKeys(T record);

The methods in IdsMapper are as follows:

 /**
	 * Queries are made according to the primary key @Id, and multiple Ids are divided by commas.
	 * @param id
	 * @return
	 */
	List<T> selectByIds(String ids);
	
	/**
	 * Delete according to the primary key @Id, and divide multiple Ids by commas
	 * @param id
	 * @return
	 */
	int deleteByIds(String ids);

The methods in ConditionMapper are as follows:

/**
	 * Query according to Condition condition
	 */
	public List<T> selectByCondition(Object condition);
 
	/**
	 * Query according to Condition condition
	 */
	public int selectCountByCondition(Object condition);
 
	/**
	 * Delete the data according to the Condition condition and return the number of deleted items
	 */
	public int deleteByCondition(Object condition);
 
	/**
	 * Update all attributes contained in entity `record'according to Condition, null values are updated, returning the number of updates
	 */
	public int updateByCondition(T record, Object condition);
 
	/**
	 * Update all attributes contained in entity `record'according to Condition, null values are updated, returning the number of updates
	 */
	public int updateByConditionSelective(T record, Object condition);

The methods in ExampleMapper are as follows:

/**
	 * Query according to Example condition
	 */
	public List<T> selectByExample(Object example);
 
	/**
	 * Query according to Example condition and throw an exception if there are more than one data
	 */
	public T selectOneByExample(Object example);
 
	/**
	 * Total number of queries based on Example conditions
	 */
	public int selectCountByExample(Object example);
 
	/**
	 * Delete data according to Example condition and return the number of deleted items
	 */
	public int deleteByExample(Object example);
 
	/**
	 * Update all attributes contained in entity `record'according to Example condition, null value will be updated, and the number of updates will be returned.
	 */
	public int updateByExample(T record, Object example);
 
	/**
	 * Update entity `record'contains attribute values other than null according to Example condition, and return the number of updates.
	 */
	public int updateByExampleSelective(T record, Object example);

Usage method

tk.mybatis.mapper.common.BaseMapper, IdsMapper, MySqlMapper internal method usage instructions:
From the interface, we can see that the input methods are basically T record, that is, entity class. When querying, where statements are constructed according to the attribute values in entity class. The query condition is equal sign. There is nothing special here.

ExampleMapper method usage instructions:

 Example example = new Example(UserModel.class);
 Example.Criteria criteria = example.createCriteria();
 criteria.andEqualTo("id","1");
 criteria.orEqualTo("userName","evan11");

Criteria is an internal class in Example, which is presented in parentheses when the final sql is constructed. Criteria takes a lot of methods to construct query conditions:

Keywords: Mybatis Spring MySQL Attribute

Added by jonsimmonds on Tue, 27 Aug 2019 14:00:11 +0300