Spring Boot integrates MyBatis's approach to accessing a database

  • 2020-06-23 00:27:46
  • OfStack

How does spring boot integrate with MyBatis?

Integration method

Feasible methods are as follows:

1. Build the necessary objects and configure MyBatis based on XML or Java Config.

2. Use the components provided by MyBatis to achieve the integration of MyBatis.

Method 1

It is recommended to refer to the following article to complete the verification of integration.

1. Introduction and configuration of MyBatis MyBatis+Spring+MySql

Based on Spring + Spring MVC + Mybatis high performance web construction

spring and mybatis3 integration methods

MyBatis Learning Summary (8) -- Integration of Mybatis3.ES44en and Spring4.ES46en

Because it is not the focus of this article, an example is not included.

Method 2

There are the following steps:

Modify ES54en. xml to increase software dependency

<dependency>
 <groupId>org.mybatis.spring.boot</groupId>
 <artifactId>mybatis-spring-boot-starter</artifactId>
 <version>1.2.0</version>
</dependency>
<dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <version>5.1.21</version>
</dependency>
Modify ES57en.yml to increase the definition of the data source

spring:

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

Modify ES73en. yml to add MyBatis configuration

mybatis:

type-aliases-package: com.example.domain.model
type-handlers-package: com.example.typehandler
configuration:
map-underscore-to-camel-case: true
default-fetch-size: 100
default-statement-timeout: 30

Log configuration

By observing the log, the SQL generated by MyBatis can be analyzed effectively and the correctness of SQL configuration can be checked.

Modify ES100en.yml to add the following configuration

logging:
level:
net:
jackieathome:
db:
mapper: DEBUG

The net. jackieathome. db. Define mapper mapper interface to access data in a database.

The output log sample is shown below

2017-04-16 11:32:23.266 DEBUG 27801 --- [io-11002-exec-1] n.j.db.mapper.UserMapper.createUser : == > Preparing: insert into `user`(id, name, password) values(?, ?, ?)
2017-04-16 11:32:23.293 DEBUG 27801 --- [io-11002-exec-1] n.j.db.mapper.UserMapper.createUser : == > Parameters: id1492313542(String), null, null
2017-04-16 11:32:23.366 DEBUG 27801 --- [io-11002-exec-1] n.j.db.mapper.UserMapper.createUser : < == Updates: 1
2017-04-16 11:32:23.372 DEBUG 27801 --- [io-11002-exec-1] n.j.db.mapper.UserMapper.findUserById : == > Preparing: select * from `user` where id = ?
2017-04-16 11:32:23.373 DEBUG 27801 --- [io-11002-exec-1] n.j.db.mapper.UserMapper.findUserById : == > Parameters: id1492313542(String)
2017-04-16 11:32:23.417 DEBUG 27801 --- [io-11002-exec-1] n.j.db.mapper.UserMapper.findUserById : < == Total: 1

Use of transactions

According to MyBatis's official documentation, it allows users to hand over transactions to Spring for management, using programming and annotations to control transactions. Here is an example of how to use it in the form of annotations. The sample code is as follows:

1. The definition of mapper is as follows


package net.jackieathome.db.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import net.jackieathome.bean.User;
@Mapper
public interface UserMapper {
 //  Create a user 
 void createUser(User user);
 //  To find the user 
 User findUserById(@Param("id") String id);
}

2. Intermediate layer code for database access, encapsulating the above mapper.

The class is marked with @Transactional to indicate that the public methods of the class are all transaction enabled. Refer to the official documentation for @Transactional.


package net.jackieathome.dao;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import net.jackieathome.bean.User;
import net.jackieathome.db.mapper.UserMapper;
@Component
@Transactional
public class UserDao {
 @Autowired
 private UserMapper userMapper;
 /**
 *  Repeatedly insert the same user data to verify that the transaction is valid 
 */
 public List<String> createBatch() {
 long time = System.currentTimeMillis() / 1000;
 User user = null;
 List<String> ids = new ArrayList<>();
 String id = "id" + time;
 String name = "name" + time;
 String password = "password" + time;
 user = new User();
 user.setId(id);
 user.setName(name);
 user.setPassword(password);
 userMapper.createUser(user);
 ids.add(id);
 user = new User();
 user.setId(id);
 user.setName(name);
 user.setPassword(password);
 userMapper.createUser(user);
 ids.add(id);
 return ids;
 }
}

3. Business layer implementation


package net.jackieathome.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import net.jackieathome.bean.User;
import net.jackieathome.dao.UserDao;
import net.jackieathome.db.mapper.UserMapper;
@RestController
public class UserController {
 @Autowired
 private UserMapper userMapper; 
 @Autowired
 private UserDao userDao;
 @RequestMapping(method = RequestMethod.GET, value = "/user/create/batch")
 public List<User> createBatch() {
 try
 {
 userDao.createBatch();
 }
 catch (Exception e)
 {
 }
 return userMapper.loadAllUsers();
 }
}

From the practical test, the implementation of the above transaction is effective, which can ensure that when the primary key conflict occurs in the data, the insert operation in the transaction can be completely cancelled, without the phenomenon of partial successful data insert and partial failure.

Notes:

Since the implementation of the annotation transaction depends on Spring AOP, control of the annotation transaction takes effect only if the injection behavior exists.

1. If the createBatch method is defined in the UserController class above and the annotation @Transactional tag is used, it is verified that the annotation transaction is invalid at this time.

2. If multiple public methods are defined in UserDao above and there is the behavior of calling each other, for the same reason, the annotation transaction will not take effect when these methods are called to each other. If you do need to ensure that transactions are available, consider tweaking the class design or controlling transactions programmatically.


Related articles: