Connecting Spring

Connecting Spring (1)
Connecting Spring (2)

1, Integrate MyBatis

The integration process is equivalent to transferring some contents written in the MyBatis configuration file to the Spring configuration file. Instead of creating objects through code, various MyBatis classes use the < bean > tag to create beans. Change the SqlSession class operating SQL to the SqlSessionTemplate class, and then add the interface implementation class. Other things basically remain unchanged.
Steps:

  1. Import related jar packages
    junit
    mybatis
    mysql
    spring
    Mybatis spring: seamlessly integrate mybatis code into spring
<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.2</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.4</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.4</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.9</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.3.9</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.6</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.20</version>
    </dependency>
  </dependencies>
  1. Write data source configuration: add the bean of DriverManagerDataSource class in the configuration file of Spring, and the properties in it are the driver, url, user name, password and other information required to connect the data
<!--data source:use Spring Data source replacement for MyBatis Configuration of-->
<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/wannado?useSSL=false"/>
    <property name="username" value="root"/>
    <property name="password" value="123654"/>
</bean>
  1. Create a bean of sqlSessionFactory: mapper.xml needs to be bound xml,mapper. The function of XML is the same as that of the original MyBatis, in which SQL statements are written
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="datasource"/>
    <!--binding MyBatis configuration file-->
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
  1. Create the bean of SqlSessionTemplate: it is equivalent to the SqlSession used in MyBatis and can perform various SQL operations. Because the object needs to be created by SqlSessionFactory, but there is no set method, the SqlSessionFactory object can only be injected through the constructor
<!--SqlSessionTemplate namely SqlSeesion-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <!--Only constructor injection can be used sqlSessionFactory,Because No set method-->
    <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
  1. Add interface implementation class: you need to add an additional class to implement the interface. You still don't need to write jdbc related code in the implementation method. You only need to create the corresponding mapper object execution method through SqlSessionTemplate.
package mapper;

import entity.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;

public class UserMapperImpl implements UserMapper{
    //All previous operations were performed through sqlSession. Now use SqlSessionTemplate
    private SqlSessionTemplate sqlSessionTemplate ;
    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate ;
    }
    //Implementation method
    public List<User> getAllUser() {
        UserMapper userMapper = sqlSessionTemplate.getMapper(UserMapper.class) ;
        return userMapper.getAllUser();
    }
}

  1. Inject the interface implementation class into Spring and test: after adding the bean of the interface implementation class to the Spring configuration file, you can test according to the normal Spring calling method
<!--Interface implementation class injection-->
<bean id="userMapper" class="mapper.UserMapperImpl">
	<!--take SqlSessionTemplate Once passed in, you can use the interface to implement the class-->
    <property name="sqlSessionTemplate" ref="sqlSession"/>
</bean>
import entity.User;
import mapper.UserMapper;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;

public class MyTest {
    @Test
    public void getAllUser() {
        try {
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml") ;
            UserMapper userDao = applicationContext.getBean("userMapper", UserMapper.class) ;
            List<User> users = userDao.getAllUser() ;
            for(User user : users) {
                System.out.println(user) ;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2, Declarative transaction

Handing over the transaction to the container for management and using AOP implementation is equivalent to crosscutting the transaction as a new function that does not affect the original function. Therefore, you only need to configure it in the Spring configuration file

  1. Add AOP and transaction constraints in the Spring configuration file
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-beans.xsd
  1. Configure declarative transaction: add the bean of DataSourceTransactionManager class to the configuration file of Spring, and you need to add a data source for it
<!--Configure declarative transactions-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="datasource"/>
</bean>
  1. Configure transaction notification: that is, determine which of the following methods to configure transactions
<!--Configure transaction notifications-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <!--Configure transactions for methods-->
    <tx:attributes>
        <tx:method name="add"/>
        <tx:method name="delete"/>
        <tx:method name="update"/>
        <!--The method name is*Represents all methods-->
        <tx:method name="*" propagation="REQUIRED"/>	
    </tx:attributes>
</tx:advice>
  1. Configure transaction entry: normal AOP configuration
<!--Configure transaction entry-->
<aop:config>
    <aop:pointcut id="txPointCut" expression="execution(* mapper.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>

Keywords: Java Mybatis Spring Framework

Added by Lord Sauron on Sun, 19 Dec 2021 13:57:33 +0200