Learn Spring Boot Together | Chapter 7: Integrating Mybatis

Keywords: Mybatis Spring xml Java

Strongly recommend

Share a great god's AI tutorial. Zero basis! Easy to understand! Funny and humorous! And yellow passages! I hope you will join the team of artificial intelligence! http://www.captainbed.net

SpringBoot is a product of simplifying the creation, operation, debugging and deployment of Spring applications. The feature of automatic assembly enables us to pay more attention to the business itself rather than the external XML configuration. We can easily build a WEB project by following the specifications and introducing relevant dependencies.

MyBatis is an excellent persistence framework. It supports customized SQL, stored procedures and advanced mapping. It avoids almost all JDBC code and manual setting of parameters and obtaining result sets. It uses simple XML or annotations to configure and map native information, and maps interfaces and Java POJOs(Plain Old Java Objects, ordinary Java objects) into records in the database. In China, it occupies half of the country...

ORM comparison diagram

Here is a rough comparison of the three frameworks ** Spring JDBC, Spring Data Jpa and Mybatis**. Ordinary application performance bottleneck is not ORM, so the three framework technology selection should consider the project scenario, team skills, development cycle (development efficiency)...

ORM comparison diagram

Here is a rough comparison of the three frameworks ** Spring JDBC, Spring Data Jpa and Mybatis**. Ordinary application performance bottleneck is not ORM, so the three framework technology selection should consider the project scenario, team skills, development cycle (development efficiency)...

Frame comparison Spring JDBC Spring Data Jpa Mybatis
performance Best performance Worst performance Centered
Code quantity many less many
Learning cost low high Centered
Recommendation Index ❤❤❤ ❤❤❤❤❤ ❤❤❤❤❤

Personal view

Regardless of learning costs, Spring Data Jpa is the fastest way to develop small and medium-sized projects with simple business. However, in view of the domestic market environment, mastering Mybatis is a good choice. The characteristics of low learning cost and dynamic SQL decoupling make it more acceptable. Mybatis is often more competent for projects with complex business and high performance requirements, and can optimize their own SQL. What I like more is that Mybatis Paging Plug-in and Universal Mapper (single form CURD does not need to be handwritten) With the support of these two plug-ins, why refuse Mybatis?

Import dependency

Add Mybatis dependency package mybatis-spring-boot-starter to pom.xml, which has the feature of automatic assembly

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<!-- MYSQL package -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Embedded by default Tomcat Containers, if needed, are extremely simple to replace.-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Test package,When we use mvn package The bag won't be punched in at the time.,Because its life cycle is limited to test within-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

Connect to the database

Like Spring Data Jpa and Spring JDBC**, you need to add the configuration of the data source in application.properties, as well as the configuration of mybatis.

spring.datasource.url=jdbc:mysql://localhost:3306/chapter6?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
# Pay attention to
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.winterchen.entity
# Hump naming conventions such as: the database field is order_id, then the entity field should be written as orderId
mybatis.configuration.map-underscore-to-camel-case=true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

mybatis.configuration.map-underscore-to-camel-case is a very good configuration item. Reasonable naming specifications can save us a lot of unnecessary troubles, such as the mapping of resultMap in xx-mapper.xml.

Specific coding

After the basic configuration is completed, the encoding operation is carried out.

Table structure

Create a table of t_user

CREATE TABLE `t_user` (
  `id` int(8) NOT NULL AUTO_INCREMENT COMMENT 'Primary key self increment',
  `username` varchar(50) NOT NULL COMMENT 'User name',
  `password` varchar(50) NOT NULL COMMENT 'Password',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='User table';
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Entity class

package com.winterchen.entity;

import java.io.Serializable;

/**
 * Created by Donghua.Chen on 2018/6/7.
 */
public class User implements Serializable {

    private static final long serialVersionUID = 8655851615465363473L;

    private Long id;
    private String username;
    private String password;

       public User() {
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public User(Long id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    // TODO omits get set
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

Persistence layer

There are two ways to operate the interface. The first one with @Select annotation is the new feature provided by Mybatis 3.x. Similarly, it has a series of annotations **@Update,@Delete,@Insert and so on. The second one is the traditional way to write an interface mapping and then write our SQL statement in XML.

UserMapper

package com.winterchen.mapper;

import com.winterchen.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * t_user Operation: Demonstrate two ways
 * <p>The first is based on the annotations provided after version 3.x of mybatis <p/>.
 * <p>The second is early writing, which writes SQL in XML <p/>.
 *
 * Created by Donghua.Chen on 2018/6/7.
 */
@Mapper
public interface UserMapper {


    /**
     * Query user result set based on user name
     *
     * @param username User name
     * @return Query results
     */
    @Select("SELECT * FROM t_user WHERE username = #{username}")
    List<User> findByUsername(@Param("username") String username);


    /**
     * Save user information
     *
     * @param user User information
     * @return Success 1 Failure 0
     */
    int insert(User user);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

UserMapper mapping file

<?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.winterchen.mapper.UserMapper">

  <insert id="insert" parameterType="com.winterchen.entity.User">
    INSERT INTO `t_user`(`username`,`password`) VALUES (#{username},#{password})
  </insert>

</mapper>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

test

After completing the data access layer interface, a junit test class is written to verify the correctness of the code.

package com.winterchen;

import com.winterchen.entity.User;
import com.winterchen.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootMybatisApplicationTests {

    private static final Logger log = LoggerFactory.getLogger(SpringBootMybatisApplicationTests.class);

    @Autowired
    private UserMapper userMapper;

    @Test
    public void test1() throws Exception {
        final int row1 = userMapper.insert(new User("u1", "p1"));
        log.info("[Add result] - [{}]", row1);
        final int row2 = userMapper.insert(new User("u2", "p2"));
        log.info("[Add result] - [{}]", row2);
        final int row3 = userMapper.insert(new User("u1", "p3"));
        log.info("[Add result] - [{}]", row3);
        final List<User> u1 = userMapper.findByUsername("u1");
        log.info("[Query by username] - [{}]", u1);
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

summary

For more Mybatis Sao operations, please refer to Official documents

At present, many big guys have written about the ** Spring Boot ** tutorial, if similar, please be more inclusive, this tutorial is based on the latest spring-boot-starter-parent: 2.0.1.RELEASE, including the features of the new version will be introduced together.

Say something

springboot Technology Exchange Group: 681513531

Personal blog: https://blog.winterchen.com

Full-text code: https://github.com/WinterChenS/springboot-learning-experience

Posted by EricTRocks on Wed, 24 Apr 2019 19:15:34 -0700