spring 事务管理

摘录:

spring并不直接管理事务,而是提供多种事务管理器,他们将事务管理的职责委托给JTA或者其他持久机制所提供的平台相关的事务实现。

imageimage

所以针对于JDBC的事务配置是:

image

针对于hibernate3的事务配置是:

image

针对于hibernate3 的某一个全部的配置是:

第五种方式:全注解

<?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-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="com.bluesky" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="sessionFactory"
            class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
</bean>
<!-- 定义事务管理器(声明式的事务) -->
<bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>

此时在DAO上需加上@Transactional注解,如下:

package com.bluesky.spring.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;
import com.bluesky.spring.domain.User;
@Transactional
@Component("userDao")
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
public List<User> listUsers() {
return this.getSession().createQuery("from User").list();
    }

}

添加事务的另外的一种方法,通过编码的方式添加:

public void saveAction(Student std){
    txTemplate.execute(new TransactionCallback<Void>() {

        @Override
        public Void doInTransaction(TransactionStatus arg0) {
            try {
                this.saveAction(std);
            } catch (Exception e) {
                arg0.setRollbackOnly();
                throw e;
            }
            return null;
        }
        
    });
}

txTemplate 为TransactionTemplate 的实例,可以通过spring配置得到。

image

这样编码的事务能够完全的控制事务的边界,但是可以看到它是侵入行的,一般的情况下,不会要求如此精确的事务边界控制,通常的情况下事务的生命放在应用的程序代码之外,例如spring配置文件中。

spring中声明式事务

image

image

image

在XML中定义事务:

image

当然,这样的配置比较的麻烦,不如上面使用注解的方式,还是推荐使用注解的方式。

原文地址:https://www.cnblogs.com/zhailzh/p/4055206.html