SpringBoot integrates MyBatis and transaction management

Integrated MyBatis

(1) Add dependency in pom.xml

        <!-- mybatis It depends on the start of. Contains mybatis,mybatis-spring,spring-jdbc(The coordinates used by the transaction) -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <!--Version number must be added to this-->
            <version>2.1.1</version>
        </dependency>
        
        <!--mysql drive-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

 

 

(2) Write entity classes with package names of model and domain

It is not necessary to mark @ Component on the entity class.

 

 

(3) Create a new package, com.chy.mapper, and write the mapper interface.

@Mapper
public interface UserMapper{
    public User queryUserById(Integer id);
}

 

 

(4) Create a new folder mapper under resource, and write the mapping file of mybatis

<?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.chy.mapper.UserMapper">
    <select id="queryUserById" parameterType="Integer" resultType="user">
        select * from user_tb where id=#{id}
    </select>
</mapper>

Notice that the namespace corresponds to the mapper interface.

Spring boot only puts java source files under src/java, configuration files, static resources and mapping files under src/resources.

 

 

(5) Write service and controller

When Mapper is injected into the service, the IDEA will display red, which is no problem.

 

 

(6) Configure the database and mybatis in the configuration file of springboot

#Configure the data source. Here, use jdbc data source and mysql database
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/my_db?serverTimezone=GMT
spring.datasource.username=chy
spring.datasource.password=abcd
        
#Configure mybatis
#Configure alias of entity class
mybatis.type-aliases-package=com.chy.model
#Specify the location of the mapping file
mybatis.mapper-locations=classpath:mapper/*Mapper.xml

Note: the key used by jdbc data source, dbcp data source and tomcat data source are different.

 

 

 

 

 

Integrating Spring's transaction management

The dependency for integrating mybatis import already contains the dependency for transaction management, so it is not necessary to add the dependency in pom.xml, just mark @ Transactional on the business method for adding transaction in service layer.

Tags: Java Mybatis Spring MySQL JDBC

Posted on Sat, 08 Feb 2020 06:05:59 -0800 by juschillinnow