Spring Hibernate Transaction示例

JDBCDAO.javajava

package com.bf;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import java.util.List; 
import java.util.Date;
import java.util.Iterator; 
 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class JDBCDAO implements SpitterDAO {
    private static String GET_SQL = "select code_item from trans_schedule where ID_NO = ?";

    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    public SpitterObj getSpitter(int ljdm) {
        return jdbcTemplate.queryForObject(GET_SQL, new RowMapper<SpitterObj>() {
            public SpitterObj mapRow(ResultSet rs, int rowNum) throws SQLException {
                SpitterObj obj = new SpitterObj();
                obj.setLOT(rs.getString(1));
                return obj;
            }
        }, ljdm);
    }
    
    private static SessionFactory factory; 
    
    public JDBCDAO() {
    } 
        
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.factory = sessionFactory;
    }
    
    public void SaveEvent(){
        factory.getCurrentSession().persist(new Event( "Our very first event!", new Date()));
       throw new RuntimeException("asdfsafd");  
    }
}
View Code

ApplicationContext.xmlspring

<?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:p="http://www.springframework.org/schema/p"
    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-3.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:" />
        <property name="username" value="" />
        <property name="password" value="" />
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg ref="dataSource" />
    </bean>
    <bean id="dao" class="com.bf.JDBCDAO" autowire="byName">
        <property name="jdbcTemplate" ref="jdbcTemplate" />
         <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <bean id="Audience" class="com.bf.Audience" autowire="byName">
    </bean>
     
       <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.Oracle9Dialect
                </prop>
            </props>
        </property>
        <property name="mappingResources">
            <list>
                <value>Event.hbm.xml</value>
            </list>
        </property>
    </bean>
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>

    <aop:config>
        <aop:pointcut id="bizServiceMethod" expression="execution(* com.bf.SpitterDAO.SaveEvent(..))" />
        <aop:advisor pointcut-ref="bizServiceMethod" advice-ref="bizAdvice" />
    </aop:config>
    
    <tx:advice id="bizAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="Save*" propagation="REQUIRED" rollback-for="Exception" />
        </tx:attributes>
    </tx:advice>
</beans>
View Code。

Spring並不直接管理事務,而是提供了多種事務管理器,它們將事務管理的職責委託給JTA(Java Transaction API)或其它持久化機制所提供的平臺相關的事務實現。如上面的HibernateTransactionManager,用於Hibernate進行持久化。sql

 

Application.javaexpress

package com.bf;

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


import java.util.List; 
import java.util.Date;
import java.util.Iterator; 
 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

@SuppressWarnings("unused")
public class Application {

    
	  public static void main(String[] args) {
	      try{
	          ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
	          
	          SpitterDAO dao = (SpitterDAO)context.getBean("dao");
	          
	          dao.SaveEvent();
	      }catch (Throwable ex) { 
	         throw new ExceptionInInitializerError(ex); 
	      }
	  }
	}

 

事務基本特性 ACID

原子性(Atomic):      事務中全部操做要麼所有完成,要麼所有不完成。apache

一致性(Consistent): 一旦事務完成(無論是成功仍是失敗),系統必須確保它所建模的業務處於一致的狀態。現實的數據不該該被損壞。session

隔離性(Isolated):    事務容許多個用戶對相同的數據進行操做,每一個用戶的操做不會與其它用戶糾纏在一塊兒。所以,事務應該被隔離,避免發生同步讀寫相同數據的事情。
併發

持久性(Durable):   一旦事務完成,事務的結果應該持久化。oracle

原子性與 隔離性確保了一致性。app

 

聲明式事務屬性

在Spring中,聲明式事務是經過事務屬性來定義的。ide

上面xml中定義的propagation="REQUIRED"表示當前方法必須運行在事務中,其它的值爲REQUIRED_NEW等。它定義事務的傳播行爲。

聲明式事務的第二個維度是隔離級別,隔離級別定義了一個事務可能受其它併發事務的影響程度。併發雖然是必須的,但可能會致使以下問題

 

 

 

另外一個版本:https://spring.io/guides/gs/managing-transactions/

相關文章
相關標籤/搜索