Spring实现声明式事务管理

基于XML方式的声明式事务

通过在配置文件中配置事务规则的相关声明来实现。用<tx:advice>元素进行配置事务的增强处理,再用AOP配置,让spring自动对目标生成代理。
<tx:advice>的属性有id,用来设置唯一标识符,还有transaction-manager,用来指定事务管理器。其子元素有<tx:method>,它有很多属性,如下:
* name:必选属性,指定了与事务属性相关的方法名,其属性支持使用通配符,如,get,handle*等
* propagation:用于指定事务的传播行为,默认值为REQUIRED
* isolation:用于指定事务的隔离级别,默认值式DEFAULT,其属性值可以是DEFAULT、READ_UNCOMMITTED、READ_COMMITTED、REPEATABLE_READ和SERIALIZABLE
* read-only:用于指定事务是否只读,默认值为false
* timeout:用于指定事务超时的时间,默认值为-1,永不超时
* rollback-for:用于指定触发事务回滚的异常类,指定多个异常类时用英文逗号分隔
* no-rollback-for:用于指定不触发事务回滚的异常类,指定多个异常类时,异常类之间用英文逗号分隔

下面时演示代码

package com.itheima.jdbc;

public class Account {
    private Integer id;
    private String username;
    private Double balance;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Double getBalance() {
        return balance;
    }

    public void setBalance(Double balance) {
        this.balance = balance;
    }

    @Override
    public String toString() {
        return "Account [id=" + id +", "
                + "username=" + username +
                ", balance=" + balance + "]";
    }
}
package com.itheima.jdbc;

import java.util.List;

public interface AccountDao {
    //添加
    public int addAccount(Account account);
    //更新
    public int updateAccount(Account account);
    //删除
    public int deleteAccount(int id);
    //通过id查询
    public Account findAccountById(int id);
    //查询所有账户
    public List<Account> findAllAccount();
    //转账
    public void transfer(String outUser, String inUser, Double money);
}

package com.itheima.jdbc;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.List;

public class AccountDaoImpl implements AccountDao{
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

//添加账号
@Override
public int addAccount(Account account) {
    //定义SQL
    String sql = "insert into account(username,balance) value(?,?)";
    //定义数组来存储SQL语句中的参数
    Object[] obj = new Object[] {
            account.getUsername(),
            account.getBalance()
    };
    //执行添加操作,返回的是受SQL语句影响的记录条数
    int num = this.jdbcTemplate.update(sql, obj);
    return num;
}

//更新账号
@Override
public int updateAccount(Account account) {
    //定义SQL
    String sql = "UPDATE account set username=?, balance=? where id=?";
    //定义数组来存储SQL语句中的参数
    Object[] params = new Object[] {
            account.getUsername(),
            account.getBalance(),
            account.getId()
    };
    //执行更新操作,返回的是受SQL语句影响的记录条数
    int num = this.jdbcTemplate.update(sql, params);
    return num;
}

//删除账号
@Override
public int deleteAccount(int id) {
    //定义SQL
    String sql = "delete from account where id = ?";
    //执行删除操作,返回的是受SQL语句影响的记录条数
    int num = this.jdbcTemplate.update(sql, id);
    return num;
}

//通过id查询账户数据信息
@Override
public Account findAccountById(int id) {
    String sql = "select * from account where id = ?";
    RowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class);
    return this.jdbcTemplate.queryForObject(sql, rowMapper, id);
}

//查询所有账号信息
@Override
public List<Account> findAllAccount() {
    String sql = "select * from account";
    RowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class);
    return this.jdbcTemplate.query(sql, rowMapper);
}

@Override
public void transfer(String outUser, String inUser, Double money) {
    this.jdbcTemplate.update("UPDATE account set balance = balance + ? " +
            "WHERE username = ?", money, inUser);
    int i = 1/0;
    this.jdbcTemplate.update("UPDATE account SET balance = balance-? " +
            "WHERE username = ?", money, outUser);
}

}

```
<?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: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/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">
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost/spring"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <bean id="accountDao" class="com.itheima.jdbc.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" read-only="false"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.itheima.jdbc.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>
package com.itheima.jdbc;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TransactionTest {
    @Test
    public void xmlTest() {
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("com/itheima/jdbc/applicationContext.xml");
        AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
        accountDao.transfer("jack", "mike", 10.0);
        System.out.println("转账成功!");
    }
}

运行测试类之后,会发现抛出0异常之后,数据库的数据还是没有变。

基于Annotation方式的声明式事务

首先在Spring容器中注册事务注解驱动,其代码如下:

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

然后在需要使用事务的Spring Bean类或者Bean类的方法上添加注解@Transactional。如果将注解添加到Bean类上,则表示事务的设置对整个Bean类的方法都起作用。如果将注解添加到Bean类中的某个方法上,则表示事务的设置只对该方法有效。
下面式@Transactional注解的参数以及描述
* value:用于指定使用的事务管理器,默认为“”,
* transactionManager:同value
* isolation:用于指定事务的隔离级别,默认为Isolation.DEFAULT,即底层事务的隔离级别
* noRollbackFor:用于指定遇到特定异常时强制不回滚事务
* noRollbackForClassName:用于指定遇到特定的多个异常时强制不回滚事务,其属性值可以指定多个异常类名
* propagation:用于指定事务的传播行为,默认为Propagation.REQUIRED
* read-only:用于指定事务是否只读,默认为false
* rollbackFor:用于指定遇到特定异常时强制回滚事务
* rollbackForClassName:用于指定遇到多个异常时强制回滚事务,其属性值可以指定多个异常类名
* timeout:用于指定事务的超时时长,默认为TransactionDefinition.TIMEOUT_DEFAULT,即用于底层事务的默认时间

下面的是演示代码:

<?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: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/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">
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost/spring"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <bean id="accountDao" class="com.itheima.jdbc.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

把在上面的AccountDaoImpl类的transfer方法上加上@Transactional注解

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false)
    public void transfer(String outUser, String inUser, Double money) {
        this.jdbcTemplate.update("UPDATE account set balance = balance + ? " +
                "WHERE username = ?", money, inUser);
        int i = 1/0;
        this.jdbcTemplate.update("UPDATE account SET balance = balance-? " +
                "WHERE username = ?", money, outUser);
    }

然后运行上面的测试类方法即可

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值