Spring常用事务

jdbc.properties文件:

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_transaction
jdbc.username=root
jdbc.password=root


log4j.properties文件:

log4j.rootLogger=WARN, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
#log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
# Print the date in ISO 8601 format
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
# Print only messages of level WARN or above in the package com.foo.
log4j.logger.com.foo=WARN

方法一:

AccountDao.java:

package cn.muke.spring.demo4;

public interface AccountDao {
    public void outMoney(String out,Double money);//转出
    public void inMoney(String in,Double money);//转入
}


AccountDaoImpl.java:

package cn.muke.spring.demo4;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{

    public void outMoney(String out, Double money) {//转出,帐号和金额
        String sql="update account set money=money-? where name=?";
        this.getJdbcTemplate().update(sql,money,out);
        
    }

    public void inMoney(String in, Double money) {//转入
        String sql="update account set money=money+? where name=?";
        this.getJdbcTemplate().update(sql,money,in);
        
    }

}

AccountService.java:

package cn.muke.spring.demo4;

public interface AccountService {
    public void transfer(String out,String in,Double i);
}

AccountServiceImpl.java:

package cn.muke.spring.demo4;

import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

//事务管理器注解
//可在注解添加传播行为等配置信息
/*
 * Transactional注解中的属性:
 * propagation    :传播行为
 * isolation    :事务的隔离级别
 * readOnly        :只读
 * rollbackFor    :发生什么异常回滚
 * noRollbackFor:发生什么异常不回回
 * */
@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT)
public class AccountServiceImpl implements AccountService {
    //注入转账的Dao类
    //提供set方法
    private AccountDao accountDao;
    public void setAccountDao(AccountDao accountDao){
        this.accountDao=accountDao;
    }
    

    public void transfer(String out,String in,Double money) {
        // in:转入帐号  out:转出帐号   money:转帐金额
        accountDao.outMoney(out, money);
        /*int i=1/0;*/
        accountDao.inMoney(in, money);
        
    }
}
TestAccount.java:

package cn.muke.spring.demo4;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/*
 * Spring声明式事务管理
 * */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext4.xml")
public class TestAccount4 {//方式3:基于注解的事务管理方式
    @Resource(name="accountService")
    private AccountService accountService;
    @Test
    public void demo1(){
        accountService.transfer("aaa", "bbb", 100d);
    }
}

applicationContext4.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        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-tx.xsd">
        
        <!-- 引入外部属性文件 (jdbc)-->
        <context:property-placeholder location="classpath:jdbc.properties"/>
        <!-- 配置C3P0连接池 -->
        <bean id="dataSource"  class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="${jdbc.driverClass}"/>
            <property name="jdbcUrl" value="${jdbc.url}"/>
            <property name="user" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </bean>
        
        <!-- 配置业务层 -->
        <bean id="accountService" class="cn.muke.spring.demo4.AccountServiceImpl">
            <property name="accountDao" ref="accountDao"/>
        </bean>
        <!-- 配置Dao层 -->
        <bean id="accountDao" class="cn.muke.spring.demo4.AccountDaoImpl">
            <!-- 将jdbc配置注入Dao层 -->
            <property name="dataSource" ref="dataSource"/>
        </bean>
        
        
        <!-- 配置事务管理器 -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!-- 开启事务注解功能 -->
        <!-- 开启之后只需要在所需要用到的类上加上注解@Transactional就好 -->
        <tx:annotation-driven transaction-manager="transactionManager"/>
        
</beans>

方法二:

AccountDao.java:

package cn.muke.spring.demo3;

public interface AccountDao {
    public void outMoney(String out,Double money);//转出
    public void inMoney(String in,Double money);//转入
}

AccountDaoImpl.java:

package cn.muke.spring.demo3;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{

    public void outMoney(String out, Double money) {//转出,帐号和金额
        String sql="update account set money=money-? where name=?";
        this.getJdbcTemplate().update(sql,money,out);
        
    }
    public void inMoney(String in, Double money) {//转入
        String sql="update account set money=money+? where name=?";
        this.getJdbcTemplate().update(sql,money,in); 
    }
}

AccountService.java:

package cn.muke.spring.demo3;

public interface AccountService {
    public void transfer(String out,String in,Double i);
}

AccountServiceImpl.java:

package cn.muke.spring.demo3;

public class AccountServiceImpl implements AccountService {
    //注入转账的Dao类
    //提供set方法
    private AccountDao accountDao;
    public void setAccountDao(AccountDao accountDao){
        this.accountDao=accountDao;
    }
    

    public void transfer(String out,String in,Double money) {
        // in:转入帐号  out:转出帐号   money:转帐金额
        accountDao.outMoney(out, money);
        /*int i=1/0;*/
        accountDao.inMoney(in, money);
    }
}
TestAccount3.java:

package cn.muke.spring.demo3;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/*
 * Spring声明式事务管理
 * */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext3.xml")
public class TestAccount3 {//方式2:基于AspectJ的XML的方式
    @Resource(name="accountService")
    private AccountService accountService;
    @Test
    public void demo1(){
        accountService.transfer("aaa", "bbb", 100d);
    }
}

applicationContext3.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        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-tx.xsd">
        
        <!-- 引入外部属性文件 (jdbc)-->
        <context:property-placeholder location="classpath:jdbc.properties"/>
        <!-- 配置C3P0连接池 -->
        <bean id="dataSource"  class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="${jdbc.driverClass}"/>
            <property name="jdbcUrl" value="${jdbc.url}"/>
            <property name="user" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </bean>
        
        <!-- 配置业务层 -->
        <bean id="accountService" class="cn.muke.spring.demo3.AccountServiceImpl">
            <property name="accountDao" ref="accountDao"/>
        </bean>
        <!-- 配置Dao层 -->
        <bean id="accountDao" class="cn.muke.spring.demo3.AccountDaoImpl">
            <!-- 将jdbc配置注入Dao层 -->
            <property name="dataSource" ref="dataSource"/>
        </bean>
        
        
        <!-- 配置事务管理器 -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
       <!--  配置事务的通知(事务的增强) -->
           <tx:advice id="txAdvice" transaction-manager="transactionManager">
               <tx:attributes>
                   <!--
                   propagation        :事务传播行为
                   isolation        :事务隔离级别
                   read-only        :只读
                   rollback-for    :发生哪些异常回滚
                   no-rollback-for    :发生哪些异常不回滚
                   timeout            :过期信息
                   -->
                   <tx:method name="transfer" propagation="REQUIRED"/>
               </tx:attributes>
           </tx:advice>
           
        <!-- 配置切面 -->
        <aop:config>
            <!-- 配置切入点: -->
            <aop:pointcut expression="execution(* cn.muke.spring.demo3.AccountService+.*(..))" id="pointcut1"/>
            <!-- 配置切面 -->
            <!-- advisor在pointcut1切入点上执行txAdvice的动作 -->
            <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut1"/>
        </aop:config>
</beans>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章