Spring事物管理

事物管理是企业级应用开发过程中必不可少的技术,用来确保数据的完整性和一致性。

事物就是一系列动作,它们被当成一个单独的工作单元,这些动作要么全部完成,要么全部不起作用。

事物的四个关键属性(ACID):

—原子性(automicity):事物是一个原子操作,由一系列动作组成。事物的原子性确保动作要么全部完成要么完全不起作用。

—一致性(consistency):一旦所有事物动作完成,事物就被提交,数据和资源就处于一种满足业务规则的一致性状态中。

—隔离性(isolation):可能有许多事物会同时处理相同的数据,因此每个事物都应该与其他事物隔离开来,防止数据损坏。

—持久性(durability):一旦事物完成,无论发生什么系统错,它的结果都不该受到影响。通常情况下,事物的结果被写到持久化存储器中。


Spring中的事物管理

- 作为企业级应用程序框架,Spring在不同的事务管理的API之上定义了一个抽象层。而应用开发人员不必了解底层事物管理API,就可以使用Spring的事物管理机制。

- Spring即支持编程式事务管理,也支持声明式事物管理。

- 编程式事务管理:将事物管理代码嵌入到业务方法中,来控制事物的提交和回滚。在编程式事务管理时,必须在每个业务操作中包含额外的事物管理代码。

- 声明式事物管理:大多数情况下比编程式事务管理更好用。它将事物管理代码从业务方法中分离出来,以声明的方式来实现事物管理。事物管理作为一种横切关注点,可以通过AOP方法模块化。Spring通过Spring AOP框架支持声明式事务管理。

物管


- Spring从不同的事物管理API中抽象了一整套的事物管理机制。开发人员不必了解底层事物API,就可以利用这些事物机制。有了这些事物机制,事物管理代码就能独立于特定的事物技术了。

- Spring的核心事物管理抽象是 Interface Platform TransactionalManager封装了一组独立于技术的方法,无论使用Spring的哪种事务管理策略(编程式或声明式),事物管理都是必须的。


以图书管理系统为例:

dao接口和实现类:

package dao_tx;

/**
 * @author chenpeng
 * @date 2018/6/4 14:27
 */
public interface BookShopDao {
    //根据书号获取书的单价
    Integer findBookPriceByIsbn(String isbn);

    //跟新书的库存,使书号对应的库存-1
    void updateBookStock(String isbn);

    //更新用户的账户余额,使username的balance-price
    void updateUserAccount(String username,int price);
}
package dao_tx;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * @author chenpeng
 * @date 2018/6/4 14:33
 */
@Repository
public class BookShopDaoImpl implements BookShopDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Integer findBookPriceByIsbn(String isbn) {
        String str = "select price from t_book where isbn = ? ";
        return jdbcTemplate.queryForObject(str,Integer.class,isbn);
    }

    @Override
    public void updateBookStock(String isbn) {
        String SQL = "select stock from t_book_stock where isbn =?";
        int stock = jdbcTemplate.queryForObject(SQL,Integer.class,isbn);

        if(stock <= 0){
            throw new BookStockException("库存不足");
        }

        String str = "update t_book_stock set stock = (stock - 1) where isbn = ? ";
        jdbcTemplate.update(str,isbn);
    }

    @Override
    public void updateUserAccount(String username, int price) {
        //验证余额
        String SQL = "select blance from t_account where user_name =?";
        int blance = jdbcTemplate.queryForObject(SQL,Integer.class,username);

        if(blance  <= price){
            throw new UserAccountException("余额不足");
        }
        String str = "update t_account set blance = (blance - ?)  where user_name = ?";
        jdbcTemplate.update(str,price,username);
    }
}


创建异常类:

package dao_tx;

/**
 * @author chenpeng
 * @date 2018/6/4 15:21
 */
public class BookStockException extends RuntimeException {
    public BookStockException() {
    }

    public BookStockException(String message) {
        super(message);
    }

    public BookStockException(String message, Throwable cause) {
        super(message, cause);
    }

    public BookStockException(Throwable cause) {
        super(cause);
    }

    public BookStockException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}
package dao_tx;

/**
 * @author chenpeng
 * @date 2018/6/4 15:20
 */
public class UserAccountException extends RuntimeException{
    public UserAccountException() {
    }

    public UserAccountException(String message) {
        super(message);
    }

    public UserAccountException(String message, Throwable cause) {
        super(message, cause);
    }

    public UserAccountException(Throwable cause) {
        super(cause);
    }

    public UserAccountException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

service层接口和实现类:

package dao_tx;

/**
 * @author chenpeng
 * @date 2018/6/4 15:28
 */
public interface BookShopService {
    void purchase(String username,String isbn);
}
package dao_tx;

import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author chenpeng
 * @date 2018/6/4 15:29
 */
public class BookShopServiceImpl implements BookShopService {

    @Autowired
    private BookShopDao bookShopDao;

    @Override
    public void purchase(String username, String isbn) {
        //1、获取书的单价
        int price = bookShopDao.findBookPriceByIsbn(isbn);
        //2、更新库存
        bookShopDao.updateBookStock(isbn);
        //3、更新用户余额
        bookShopDao.updateUserAccount(username,price);
    }
}


关于配置文件:

<?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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--导入资源文件-->
    <context:property-placeholder location="db.properties"/>

    <!--扫描-->
    <context:component-scan base-package="dao_tx"/>

    <!--配置c3p0数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${driver}"/>
        <property name="jdbcUrl" value="${url}"/>
        <property name="user" value="${user}"/>
        <property name="password" value="${password}"/>

        <property name="initialPoolSize" value="${initPoolSize}"/>
        <property name="maxPoolSize" value="${maxPoolSize}"/>
    </bean>

    <!--配置Spring的jdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>


    <!--配置NamedParameterJdbcTemplate,该对象可以使用具名参数,其没有无参构造器,所以必须为其构造器指定参数-->
    <bean id="NamedParameterJdbcTemplate"
          class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
        <constructor-arg ref="dataSource"/>
    </bean>


</beans>


添加事务管理:

1、在配置文件中配置事物管理器和启用事务注解

2、在相应的方法上加上@TransactionManager注解

<!--配置事务管理器-->
<bean id="transactionManager"
      class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

<!--启用事务注解-->
<tx:annotation-driven transaction-manager="transactionManager"/>
//添加事务注解
@Transactional
@Override
public void purchase(String username, String isbn) {
    //1、获取书的单价
    int price = bookShopDao.findBookPriceByIsbn(isbn);
    //2、更新库存
    bookShopDao.updateBookStock(isbn);
    //3、更新用户余额
    bookShopDao.updateUserAccount(username,price);
}


原文地址:https://www.cnblogs.com/huangzhe1515023110/p/9276053.html