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) -->
            <!--Version number must be added to this-->
        <!--mysql drive-->



(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.

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"

<mapper namespace="com.chy.mapper.UserMapper">
    <select id="queryUserById" parameterType="Integer" resultType="user">
        select * from user_tb where id=#{id}

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
#Configure mybatis
#Configure alias of entity class
#Specify the location of the mapping file

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