Java-spring Learning - Integrating mybatis and spring, configuring transactions for spring

Posted by CodeMaster on Tue, 30 Jul 2019 11:44:40 +0200

Articles Catalogue

Integrating mybatis and spring

1. First, recall the steps to write the mybatis project

  • Import database

  • Guide bag

    • junit
    • mybatis
    • mysql connection driver
  • Write entity classes based on databases

  • Write mybatis configuration file (mybatis-config.xml)

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        ...
    </configuration>    
    
  • Writing interfaces

  • Write mapper mapping file corresponding to interface

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="[Interface]">
        ...
    </mapper>
    
  • Register mapper mapping file in mybatis-config.xml

     <mappers>
            <mapper resource="../[mapper.xml]"/>
     </mappers>
    
  • Write test files

    InputStream resource = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            UserDao mapper = sqlSession.getMapper([Interface name].class);
    

2.Spring integrates MyBatis

[Preliminary preparation]

Understanding an important package: MyBatis-Spring

MyBatis-Spring: http://www.mybatis.org/spring/zh

Let's go and have a look. I've extracted some knowledge points that need to be known:

  • The role of MyBatis-Spring:

    MyBatis-Spring will help you seamlessly integrate MyBatis code into Spring

  • The required version of MyBatis-Spring:
    MyBatis-Spring MyBatis Spring Framework Spring Batch Java
    2.0 3.5+ 5.0+ 4.0+ Java 8+
    1.3 3.4+ 3.2.2+ 2.1+ Java 6+

    According to my own situation, I chose version 1.3.

    Guide packages:

    I use Maven as a build tool, so I just need to add the following code in pom.xml:

    <!-- The version I chose is 1.3.2 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.2</version>
    </dependency>
    
  • How to use MyBatis with Spring:
    • On sqlSession Factory

      In the basic MyBatis usage, SqlSession Factory is created through SqlSession Factory Builder. In MyBatis-Spring, SqlSessionFactory Bean can be used to create SqlSessionFactory. To configure the factory bean, just put the following code in Spring's XML configuration file:

      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
      </bean>
      

      Note: SqlSession Factory needs a Data Source. This can be any DataSource, just configure it as you configure other Spring database connections.

    • On SqlSession

      In MyBatis, you can use SqlSession Factory to create SqlSession. Once you have a session, you can use it to execute mapped statements, submit or roll back connections, and finally close the session when it is no longer needed. With MyBatis-Spring, you no longer need to use SqlSession Factory directly, because your bean can be injected into a thread-safe SqlSession, which can automatically commit, rollback, and close sessions based on Spring's transaction configuration.

    • On SqlSession Template

      SqlSession Template is the core of MyBatis-Spring.

      As an implementation of SqlSession, this means that it can seamlessly replace the SqlSession already in use in your code. SqlSession Template is thread-safe and can be shared by multiple DAO s or mappers.

      SqlSessionTemplate objects can be created using SqlSessionFactory as a parameter to the constructor.

      <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
      </bean>
      

[Example]

Look at the front, you may be a bit confused, so let's write a project directly.

Overall project structure:

<1. Guide Pack
       <!--unit testing-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>

        <!--mybaits-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

        <!--mysql Connection Driver-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!--Spring Package-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>


        <!--mybatis-spring-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>

<2. Configure mybatis file

Simply write some simple settings, aliases and register mapper mapping files

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <!--Alias-->
    <typeAliases>
        <package name="priv.sehun.pojo"/>
    </typeAliases>

    <!--Registration mapping file-->
    <mappers>
        <mapper resource="priv/sehun/dao/UserMapper.xml"/>
    </mappers>

</configuration>
< 3. Write spring configuration file

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--1.Configuring data sources,What we're using is spring A third-party data source can also be used-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!--2.To configure SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--Relation mybatis Configuration file-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!--3.Establish selSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    </bean>

    <!--4.Interface Implementing Class Injection sqlSession-->
    <!--Deliver the implementation class of the interface to spring To manage-->
    <bean id="userDaoImpl" class="priv.sehun.dao.UserDaoImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>


</beans>
<4. Interface, Interface Implementation Class, Interface Mapping File

UserDao

public interface UserDao {
    //Get all user information
    List<User> selectUser();
}

UserDaoImpl

import org.mybatis.spring.SqlSessionTemplate;
import priv.sehun.pojo.User;

import java.util.List;

public class UserDaoImpl implements UserDao {

    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    public List<User> selectUser() {

        UserDao mapper = sqlSession.getMapper(UserDao.class);
        return mapper.selectUser();

    }
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="priv.sehun.dao.UserDao">
    <select id="selectUser" resultType="User">
        select * from mybatis.user
    </select>
</mapper>
< 5. Test class

Note, don't mistake the bag.

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import priv.sehun.pojo.User;

import java.util.List;

public class UserTest {
    @Test
    public void test(){
        //Parse the beans.xml configuration file and manage the corresponding Bean objects in production.
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        //Get the entity of the object through the Bean
        UserDao userDaoImpl = (UserDao) context.getBean("userDaoImpl");
        List<User> users = userDaoImpl.selectUser();

        for (User user : users) {
            System.out.println(user);
        }
    }
}

<6 Running results

affair

Transaction Details

See a blog: https://blog.csdn.net/weixin_40263776/article/details/79521595

Detailed description of Java transactions, why Java transactions are needed, and the types of Java transactions.

Configure transactions for spring

Spring supports two transaction processing mechanisms:

  • Programming Transactions: Write the code of all transactions in the business;
  • Declarative transactions: use AOP to cross-cut in;

General use of declarative transactions

code implementation

  1. Guide bag

  2. A transaction manager needs to be configured, and a data source is needed for the parameters.

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="dataSource" />
    </bean>
    
  3. Configuration declaration transaction notification

    <! - Configuration declaration transaction notification - >
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--
            name: Which methods use transactions [methods]
            Propagation: Configuring the propagation characteristics of transactions
            REQUIRED: If there is no transaction, create a new one.
            -->
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
    
        </tx:attributes>
    </tx:advice>
    
  4. Configure aop to weave transactions

    <!--To configure aop Weave in business-->
    <aop:config>
        <!--breakthrough point-->
        <aop:pointcut id="txPointCut" expression="execution(* com.kuang.dao.UserDaoImpl.*(..))"/>
        <!--notice-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
    

Developing with annotations

bean
  1. Guide package;

  2. Add a constraint in the configuration file: context;

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    
  3. Configure Scanning Component

    <! - Auto-scan the annotations under the specified package - >
    <context:component-scan base-package="priv.sehun.demo"/>
    
  4. Write code:

    //Equivalent to: <bean id="user1" class="priv.sehun.demo.User"/>
    
    /*
    @Component : Component bean s
    @Controller : web layer
    @Service :  service layer
    @Repository : dao layer
     */
    
    @Component("user1")
    public class User1 {
        public String name = "Dog";
    }
    
IOC injection
  1. Instead of providing a set method, you can add an @Values (value) directly to the attribute name.
@Controller("user2")
public class User2 {
    @Value("Dog")
    private String name;

    public String getName() {
        return name;
    }
}
  1. If there is a set, add @Values (value) directly to the set method.
@Controller("user2")
public class User2 {
    private String name;

    public String getName() {
        return name;
    }
    
    @Value("Qin Jiang")
    public void setName(String name) {
        this.name = name;
    }
}

Topics: Mybatis Spring xml Java