Spring (seven)

Spring's transaction management

       Transaction Management way:

  1. Programmatic transaction management

Transaction management is achieved by writing code, including the definition of the beginning of the transaction, the transaction after the normal and abnormal commit transaction rollback

  1. Declarative transaction management

Transaction management is achieved through AOP technology, the main idea is to manage affairs as an "aspect" code written separately and then by AOP transaction management technology will "cut" the code woven into the business target class

       Declarative transaction management in two ways:

       1, based on xml declarative transaction management approach is relevant statement by the configuration of business rules in the configuration file to achieve. Spring2.0 later, a configuration transaction x namespace for the next tx namespace <tx: advice> element to configure the notification transaction (enhancement processing). When: After <tx advice> element configures the enhanced processing services, you can write by AOP configuration, make Spring automatically generate the proxy target.

       Example code:

              1. Project architecture 

       2, the relevant jar package

  1. Dao dao write interfaces and implementation classes

dao Interface

public interface AccountDao {

 

// transfer method

public void transfer(String outUser,String inUser,Double money);

 

}

        dao interface class

                            public class AccountDaoImpl implements AccountDao {

 

       private JdbcTemplate jdbcTemplate;

 

       public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {

              this.jdbcTemplate = jdbcTemplate;

       }

 

       // transaction implementation method

       @Override

       public void transfer(String outUser, String inUser, Double money) {

              // TODO Auto-generated method stub

              When // receivables, receivables user's available funds balance + = amount remitted

              this.jdbcTemplate.update(

                            "update account set balance = balance+? where username=?",

                            money, inUser);

             

              // 0 denominator can not do so there must appear bug

              int i = 1/0;

             

              When // remittances, remittances user's balance = existing funds - the amount remitted

              this.jdbcTemplate.update(

                            "update account set balance = balance-? where username=?",

                            money, outUser);

             

       }

 

}

  1. Profiles:

<! - 1, configuration data source ->

<bean id="dataSource"

        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

 

        <-! Database-driven ->

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />

        <! - link to the database url ->

        <property name="url" value="jdbc:mysql://localhost:3306/demo" />

        <! - username link to the database ->

        <property name="username" value="root" />

        <-! Password link the database ->

        <property name="password" value="123456" />

 

</bean>

 

<-! 2, configure JDBC template inside a good package of crud (CRUD) code uses the premise is you must first link to the database ->

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">

 

        <! - default must use a data source ->

        <property name="dataSource" ref="dataSource" />

 

</bean>

 

<! - 3, is defined as the id of accountDao bean ->

<bean id="accountDao" class="com.bdqn.cn.dao.AccountDaoImpl">

 

 

        <property name="jdbcTemplate" ref="jdbcTemplate" />

 

 

</bean>

 

<! - 4, the transaction manager, depending on the data source ->

<bean id="transactionManager"

        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

 

        <property name="dataSource" ref="dataSource" />

 

</bean>

 

<-! 5, written notice: transaction enhanced (notice), you need to write the details of the enforcement branch point and Juin ->

<tx:advice id="txAdvice" transaction-manager="transactionManager">

 

        <tx:attributes>

       

               <!--

                      propagation = "REQUIRED" is used to specify the default is REQUIRED propagation behavior Affairs

                      isolation = "DEFAULT" is used to specify the transaction isolation level

                      read-only = "false" specifies whether a read-only transaction

               -->

             <tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" read-only="false"/>

       

        </tx:attributes>

 

</tx:advice>

 

<-! 6, write aop, let the spring automatically generate a proxy target, you need to use the expression of AspecJ ->

<aop:config>

 

        <! - Configuration entry point ->

        <aop:pointcut expression="execution(* com.bdqn.cn.dao.*.*(..))" id="txPointcut"/>

        <- section:! Point and notify the Integration ->

        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>

 

</aop:config>

5, write test classes:

public class testDemo {

      

       @Test

       public void method(){

              ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");

              AccountDao ad = (AccountDao) app.getBean("accountDao");

              ad.transfer ( "Joe Smith", "John Doe", 1000.0);

              System.out.println ( "transfer success!");

       }

      

}

 

  1. Based Programming notes (annotation) of

Example code:

       public class AccountDaoImpl implements AccountDao {

 

       private JdbcTemplate jdbcTemplate;

 

       public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {

              this.jdbcTemplate = jdbcTemplate;

       }

 

       @Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT,readOnly=false)

       @Override

       public void transfer(String outUser, String inUser, Double money) {

              // TODO Auto-generated method stub

              When // receivables, receivables user's available funds balance + = amount remitted

              this.jdbcTemplate.update(

                            "update account set balance = balance+? where username=?",

                            money, inUser);

             

              // 0 denominator can not do so there must appear bug

//            int i = 1/0;

             

              When // remittances, remittances user's balance = existing funds - the amount remitted

              this.jdbcTemplate.update(

                            "update account set balance = balance-? where username=?",

                            money, outUser);

             

       }

 

}

       Profiles:

       <! - 1, configuration data source ->

       <bean id="dataSource"

              class="org.springframework.jdbc.datasource.DriverManagerDataSource">

 

              <-! Database-driven ->

              <property name="driverClassName" value="com.mysql.jdbc.Driver" />

              <! - link to the database url ->

              <property name="url" value="jdbc:mysql://localhost:3306/demo" />

              <! - username link to the database ->

              <property name="username" value="root" />

              <-! Password link the database ->

              <property name="password" value="123456" />

 

       </bean>

 

       <-! 2, configure JDBC template inside a good package of crud (CRUD) code uses the premise is you must first link to the database ->

       <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">

 

              <! - default must use a data source ->

              <property name="dataSource" ref="dataSource" />

 

       </bean>

 

       <! - 3, is defined as the id of accountDao bean ->

       <bean id="accountDao" class="com.bdqn.cn.dao.AccountDaoImpl">

 

 

              <property name="jdbcTemplate" ref="jdbcTemplate" />

 

 

       </bean>

 

       <! - 4, the transaction manager, depending on the data source ->

       <bean id="transactionManager"

              class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

 

              <property name="dataSource" ref="dataSource" />

 

       </bean>

 

       <-! 5, Regulatory Affairs Manager Driver ->

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

Spring + MyBatis integration

       Example code:

              Required jar package

             

              Project Architecture:

             

              Dao interface and implementation class:

              public class CustomerDaoImpl extends SqlSessionDaoSupport implements

              CustomerDao {

      

       // query by id

       @Override

       public Customer findCustomerById(Integer id) {

 

              return this.getSqlSession().selectOne(

                            "com.bdqn.cn.pojo.CustomerMapper.findCustomerById", id);

       }

 

}

       Mapper configuration file:

       <mapper namespace="com.bdqn.cn.pojo.CustomerMapper">

 

       <select id="findCustomerById" parameterType="Integer" resultType="customer">

              select * from Customer where id=#{id}

       </select>

      

</mapper>

Spring configuration file:

       <context:property-placeholder location="db.properties"/>

 

       <! - 1, configuration data source ->

       <bean id="dataSource"

              class="org.springframework.jdbc.datasource.DriverManagerDataSource">

 

              <-! Database-driven ->

              <property name="driverClassName" value="${driver}" />

              <! - link to the database url ->

              <property name="url" value="${url}" />

              <! - username link to the database ->

              <property name="username" value="${username}" />

              <-! Password link the database ->

              <property name="password" value="${password}" />

 

       </bean>

 

       <! - Configure the transaction manager, depending on the data source ->

       <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

      

              <property name="dataSource" ref="dataSource" />

      

       </bean>

      

       <! - open transaction comment ->

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

      

       <! - Configure mybatis plant ->

       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

      

              <! - injecting Data Source ->

              <property name="dataSource" ref="dataSource" />

              <! - Specifies the core profile ->

              <property name="configLocation" value="classpath:mybatis-config.xml" />

      

      

       </bean>

      

       <bean id="customerDao" class="com.bdqn.cn.dao.CustomerDaoImpl">

      

              <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>

      

       </bean>

       Mybatis profile:

       <configuration>

    <! - Type aliases ->

    <typeAliases>

        <package name="com.bdqn.cn.pojo" />

    </typeAliases>

    <mappers>

           <mapper resource="com/bdqn/cn/pojo/CustomerMapper.xml" />

    </mappers>

</configuration>

Published 40 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/sj_1993/article/details/105250617