Spring a set of all pass 4 - persistent layer integration

Keywords: Java

Baizhi Education - Spring series courses - persistent layer integration

Chapter I. persistent layer integration

1. Why does spring framework integrate with persistence layer technology
1. JavaEE The development needs the persistence layer to access the database.
2. JDBC Hibernate MyBatis There is a lot of code redundancy in the process of persistent development
3. Spring The above persistent layer technology is encapsulated based on template design pattern
2. What persistence layer technologies can spring integrate with?
1. JDBC
     |-  JDBCTemplate 
2. Hibernate (JPA)
     |-  HibernateTemplate
3. MyBatis
     |-  SqlSessionFactoryBean MapperScannerConfigure 

Chapter 2. Integration of Spring and MyBatis

1. Review of mybatis development steps
1. entity
2. Entity alias  
3. surface
4. establish DAO Interface
5. realization Mapper file
6. register Mapper file
7. MybatisAPI call
2. Problems in mybatis development
Configuration code redundancy 

1. entity
2. Entity alias         Cumbersome configuration 
3. surface
4. establish DAO Interface
5. realization Mapper file
6. register Mapper Cumbersome file configuration 
7. MybatisAPI Call code redundancy 
3. Analysis of integration ideas between spring and Mybatis

4. Development steps of spring and Mybatis integration
  • Configure the configuration file (ApplicationContext.xml)

    #Configuration is required once 
    <bean id="dataSource" class=""/> 
    
    <!--establish SqlSessionFactory-->
    <bean id="ssfb" class="SqlSessionFactoryBean">
        <property name="dataSource" ref=""/>
        <property name="typeAliasesPackage">
             Specifies the package where the entity class is located  com.baizhiedu.entity  User
                                                     Product
        </property>
        <property name="mapperLocations">
              Specify profile(Mapping file)There is also a common configuration for the path 
              com.baizhiedu.mapper/*Mapper.xml 
        </property>
    </bean>
    
    <!--DAO Implementation class of interface
        session ---> session.getMapper() --- xxxDAO Implementation class object 
        XXXDAO  ---> xXXDAO
    -->
    <bean id="scanner" class="MapperScannerConfigure">
        <property name="sqlSessionFactoryBeanName" value="ssfb"/>
        <property name="basePacakge">
            appoint DAO Package placed by interface  com.baizhiedu.dao 
        </property>
    </bean>
    
  • code

    # Code often written according to requirements in actual combat
    1. entity
    2. surface
    3. establish DAO Interface
    4. realization Mapper file
    
5. Spring and Mybatis integrated coding
  • Build development environment (jar)

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.1.14.RELEASE</version>
    </dependency>
    
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.2</version>
    </dependency>
    
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.18</version>
    </dependency>
    
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.48</version>
    </dependency>
    
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>
    
  • Configuration of Spring configuration file

    <!--Connection pool-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
      <property name="url" value="jdbc:mysql://localhost:3306/suns?useSSL=false"></property>
      <property name="username" value="root"></property>
      <property name="password" value="123456"></property>
    </bean>
    
    <!--establish SqlSessionFactory SqlSessionFactoryBean-->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource"></property>
      <property name="typeAliasesPackage" value="com.baizhiedu.entity"></property>
      <property name="mapperLocations">
        <list>
          <value>classpath:com.baizhiedu.mapper/*Mapper.xml</value>
        </list>
      </property>
    </bean>
    
    <!--establish DAO object MapperScannerConfigure-->
    
    <bean id="scanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
      <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"></property>
      <property name="basePackage" value="com.baizhiedu.dao"></property>
    </bean>
    
  • code

    1. entity
    2. surface
    3. DAO Interface
    4. Mapper File configuration
    
6. Details of spring and Mybatis integration
  • Question: after the integration of Spring and Mybatis, why does the DAO not commit transactions, but the data can be inserted into the database?

    Connection --> tx
    Mybatis(Connection)
    
    Essentially controls connected objects(Connection) ---> Connection pool(DataSource)
    1. Mybatis Provided connection pool object ---> establish Connection
         Connection.setAutoCommit(false) The transaction is controlled manually. After the operation is completed, it is submitted manually
    2. Druid(C3P0 DBCP)As connection pool        ---> establish Connection
         Connection.setAutoCommit(true) true The default value maintains automatic control transactions, one sql Auto submit 
    Answer: because Spring And Mybatis During consolidation, the external connection pool object is introduced to maintain the automatic transaction submission mechanism(Connection.setAutoCommit(true)),Transaction submission can be performed without manual transaction operation 
    
    Note: in the future, transactions will be controlled manually(Multiple sql Success and failure together),follow-up Spring This problem is solved through transaction control.
    

Chapter 3: Spring transaction processing

1. What is a transaction?
A database mechanism to ensure the integrity of business operations

Transaction 4 features: A C I D
1. A Atomicity
2. C uniformity
3. I Isolation
4. D persistence
2. How to control transactions
JDBC:
    Connection.setAutoCommit(false);
    Connection.commit();
    Connection.rollback();
Mybatis: 
    Mybatis Auto start transaction
    
    sqlSession(Connection).commit();
    sqlSession(Connection).rollback();

Conclusion: the underlying control transactions are Connection Object completed.
3. Development of spring control transaction
Spring Yes AOP Transaction development
1. Original object
public class XXXUserServiceImpl{
   private xxxDAO xxxDAO
   set get

   1. Original object ---> Original method --->Core functions (Business processing+DAO call)
   2. DAO As Service The member variable of depends on the method of injection
}
2. Additional functions
1. org.springframework.jdbc.datasource.DataSourceTransactionManager
2. injection DataSource 
1. MethodInterceptor
   public Object invoke(MethodInvocation invocation){
      try{
        Connection.setAutoCommit(false);
        Object ret = invocation.proceed();
        Connection.commit();
      }catch(Exception e){
        Connection.rollback();
      }
        return ret;
   }
2. @Aspect
   @Around 
3. Entry point
@Transactional 
Additional functionality of transactions is added to those business methods.

1. On class: all methods in the class will join the transaction
2. Method: this method will join the transaction
4 assembly section
1. breakthrough point
2. Additional features

<tx:annotation-driven transaction-manager=""/>
4. Spring controls the encoding of transactions
  • Build development environment (jar)

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.1.14.RELEASE</version>
    </dependency>
    
  • code

    <bean id="userService" class="com.baizhiedu.service.UserServiceImpl">
      <property name="userDAO" ref="userDAO"/>
    </bean>
    
    <!--DataSourceTransactionManager-->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource" ref="dataSource"/>
    </bean>
    
    @Transactional
    public class UserServiceImpl implements UserService {
        private UserDAO userDAO;
    
    <tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
    
  • details

    <tx:annotation-driven transaction-manager="dataSourceTransactionManager" proxy-target-class="true"/>
    Switch the underlying implementation of dynamic agent   proxy-target-class
        default false JDK
            true  Cglib 
    

Chapter 4 transaction attribute in Spring

1. What are transaction attributes
Attribute: a series of values that describe the characteristics of an object
     Gender height weight ...
Transaction attribute: a series of values that describe the characteristics of a transaction 
1. Isolation properties
2. Propagation properties
3. Read only attribute
4. Timeout attribute
5. Exception properties 
2. How to add transaction attributes
@Transactional(isloation=,propagation=,readOnly=,timeout=,rollbackFor=,noRollbackFor=,)
3. Detailed explanation of transaction attributes
1. Isolation attribute
  • Concept of isolation attribute

    Concept: he describes the characteristics of transaction solving concurrency problems
    1. What is concurrency
           Multiple transactions(user)The same data is accessed at the same time
           
           Same time: 0.000 A few seconds ago
    2. What are the problems with concurrency
           1. Dirty reading
           2. Non repeatable reading
           3. Phantom reading
    3. How to solve the concurrency problem
           Different values are set in the isolation attribute to solve the problems in concurrent processing.
    
  • Problems caused by transaction concurrency

    • Dirty reading

      A transaction reads uncommitted data from another transaction. Data inconsistency will occur in this transaction
       Solution  @Transactional(isolation=Isolation.READ_COMMITTED)
      
    • Non repeatable reading

      In a transaction, the same data is read multiple times, but the reading results are different. Data inconsistency will occur in this transaction
       Note: 1 is not a dirty read. 2 is in a transaction
       Solution @Transactional(isolation=Isolation.REPEATABLE_READ)
      Essence: a row lock
      
    • Phantom reading

      In a transaction, the whole table is queried and counted many times, but the results are different, which will cause the problem of inconsistent data in this transaction
       Solution @Transactional(isolation=Isolation.SERIALIZABLE)
      Essence: table lock 
      
    • summary

      Concurrency security: SERIALIZABLE>REPEATABLE_READ>READ_COMMITTED
       Operating efficiency: READ_COMMITTED>REPEATABLE_READ>SERIALIZABLE
      
  • Database support for isolation properties

    Value of isolation property MySQL Oracle
    ISOLATION_READ_COMMITTED
    IOSLATION_REPEATABLE_READ
    ISOLATION_SERIALIZABLE
    Oracle I won't support it REPEATABLE_READ How to solve the problem of non readability
     Multi version comparison is adopted to solve the problem of non repeatable reading
    
  • Default isolation properties

    ISOLATION_DEFAULT: The default isolation properties set by different databases will be called
    
    MySQL : REPEATABLE_READ 
    Oracle: READ_COMMITTED  
    
    • View database default isolation properties

      • MySQL

        select @@tx_isolation;
        
      • Oracle

        SELECT s.sid, s.serial#,
           CASE BITAND(t.flag, POWER(2, 28))
              WHEN 0 THEN 'READ COMMITTED'
              ELSE 'SERIALIZABLE'
           END AS isolation_level
        FROM v$transaction t 
        JOIN v$session s ON t.addr = s.taddr
        AND s.sid = sys_context('USERENV', 'SID');
        
  • Suggestions of isolation attribute in practice

    Recommended use Spring designated ISOLATION_DEFAULT
     1. MySQL   repeatable_read
     2. Oracle  read_commited 
    
    In the future actual combat, the situation of concurrent access is very low 
    
    If you really encounter concurrency problems, optimistic locking 
       Hibernate(JPA)  Version 
       MyBatis         Custom development through interceptors
     
    
2. Propagation attribute
  • Concept of propagation attributes

    Concept: he describes the characteristics of transaction solving nested problems
    
    What is called transaction nesting: it refers to a large transaction that contains several small transactions
    
    Problem: many small transactions are integrated into large transactions. They affect each other, which will eventually lead to external large transactions and lose the atomicity of transactions
    
  • Value of propagation property and its usage

    Propagate the value of the property External transaction does not exist External transaction usage remarks
    REQUIRED Open a new transaction Merge into external transactions @Transactional(propagation = Propagation.REQUIRED) Addition, deletion and modification method
    SUPPORTS Do not open transaction Merge into external transactions @Transactional(propagation = Propagation.SUPPORTS) Query method
    REQUIRES_NEW Open a new transaction Suspend external transactions and create new transactions @Transactional(propagation = Propagation.REQUIRES_NEW) In the logging method
    NOT_SUPPORTED Do not open transaction Suspend external transactions @Transactional(propagation = Propagation.NOT_SUPPORTED) And rarely used
    NEVER Do not open transaction Throw exception @Transactional(propagation = Propagation.NEVER) And rarely used
    MANDATORY Throw exception Merge into external transactions @Transactional(propagation = Propagation.MANDATORY) And rarely used
  • Default propagation properties

    REQUIRED Is the default value for propagation properties
    
  • Recommended usage of propagation properties

    Addition, deletion and modification method: directly use the default value REQUIRED 
    Query operation: displays the value of the specified propagation attribute as SUPPORTS  
    
3. Read only attribute (readOnly)
For business methods that only perform query operations, read-only attributes can be added to provide operation efficiency

Default: false 
4. Timeout attribute
Specifies the maximum time for the transaction to wait

1. Why do transactions wait?
   When the current transaction accesses data, the data that may be accessed is locked by other transactions. At this time, the transaction must wait.
2. Wait time seconds
3. How to apply @Transactional(timeout=2)
4. Default value for timeout property -1 
   Finally, it is specified by the corresponding database
5. Exception attributes
Spring During transaction
 Default for RuntimeException And its subclasses adopt the rollback strategy
 Default for Exception And its subclasses adopt the submission strategy

rollbackFor = {java.lang.Exception,xxx,xxx} 
noRollbackFor = {java.lang.RuntimeException,xxx,xx}

@Transactional(rollbackFor = {java.lang.Exception.class},noRollbackFor = {java.lang.RuntimeException.class})

Suggestion: use in actual combat RuntimeExceptin And its subclasses use the default value of the transaction exception attribute
4. Summary of common configurations of transaction attributes
1. Isolation attribute defaults 
2. Propagation properties   Required(Default value) Addition, deletion and modification   Supports Query operation
3. Read only attribute   readOnly false  Addition, deletion and modification   true Query operation
4. Timeout attribute default -1
5. Exception attribute default 

Addition, deletion and modification   @Transactional
 Query operation     @Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
5. Tag based transaction configuration (the second form of transaction development)
Annotation based @Transaction Transaction configuration review for
<bean id="userService" class="com.baizhiedu.service.UserServiceImpl">
  <property name="userDAO" ref="userDAO"/>
</bean>

<!--DataSourceTransactionManager-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource"/>
</bean>

@Transactional(isolation=,propagation=,...)
public class UserServiceImpl implements UserService {
    private UserDAO userDAO;

<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>

Label based transaction configuration
<bean id="userService" class="com.baizhiedu.service.UserServiceImpl">
  <property name="userDAO" ref="userDAO"/>
</bean>

<!--DataSourceTransactionManager-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource"/>
</bean>

Transaction properties 
<tx:advice id="txAdvice" transacation-manager="dataSourceTransactionManager">
    <tx:attributes>
          <tx:method name="register" isoloation="",propagation=""></tx:method>
          <tx:method name="login" .....></tx:method>
          Equivalent to 
          @Transactional(isolation=,propagation=,)
          public void register(){
        
          }
      
    </tx:attributes>
</tx:advice>

<aop:config>
     <aop:pointcut id="pc" expression="execution(* com.baizhiedu.service.UserServiceImpl.register(..))"></aop:pointcut>
     <aop:advisor advice-ref="txAdvice" pointcut-ref="pc"></aop:advisor>
</aop:config>
  • Application of tag based transaction configuration in practice

    <bean id="userService" class="com.baizhiedu.service.UserServiceImpl">
      <property name="userDAO" ref="userDAO"/>
    </bean>
    
    <!--DataSourceTransactionManager-->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource" ref="dataSource"/>
    </bean>
    
    Programming time service The methods responsible for adding, deleting and modifying operations in modify start
                           It doesn't matter whether the query operation is named 
    <tx:advice id="txAdvice" transacation-manager="dataSourceTransactionManager">
        <tx:attributes>
              <tx:method name="register"></tx:method>
              <tx:method name="modify*"></tx:method>
              <tx:method name="*" propagation="SUPPORTS"  read-only="true"></tx:method>
        </tx:attributes>
    </tx:advice>
    
    In the process of application, service Place to service Package
    <aop:config>
         <aop:pointcut id="pc" expression="execution(* com.baizhiedu.service..*.*(..))"></aop:pointcut>
         <aop:advisor advice-ref="txAdvice" pointcut-ref="pc"></aop:advisor>
    </aop:config>
    

Posted by RyanSmith345 on Mon, 08 Nov 2021 11:45:48 -0800