Spring聲明式事務配置與使用

一、配置:html

<context:component-scan base-package="com.vrvwh.wh01" />
<
bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <property name="maxActive" value="50" /> <property name="initialSize" value="1" /> <property name="maxWait" value="60000" /> <property name="minIdle" value="1" /> <property name="timeBetweenEvictionRunsMillis" value="3000" /> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="SELECT 'x' FROM DUAL" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- mysql 不支持 poolPreparedStatements --> <!--<property name="poolPreparedStatements" value="true" /> --> <!--<property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> --> <!-- 開啓Druid的監控統計功能 --> <property name="filters" value="stat" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan"> <list> <value>com.vrvwh.wh01.domain</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=${dialect} hibernate.show_sql=${hibernate.show_sql} hibernate.hbm2ddl.auto=${hibernate.hbm2ddl.auto} cache.provider_class=${hibernate.cache.provider_class} cache.use_second_level_cache=${hibernate.cache.use_second_level_cache} cache.use_query_cache=${hibernate.cache.use_query_cache} hibernate.jdbc.batch_size=${hibernate.jdbc.batch_size} </value> </property> </bean> <!-- 配置Hibernate事務管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置事務異常封裝 --> <bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /> <tx:annotation-driven transaction-manager="transactionManager"/>

二、使用java

public Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

 public Serializable save(T instance) {
        return getCurrentSession().save(instance);
    }

 注意:mysql

sessionFactory.getCurrentSession() 才能在事務中運行

在單獨使用不帶任何參數的  註釋時,傳播模式要設置爲 ,只讀標誌設置爲 ,事務隔離級別設置爲 ,並且事務不會針對受控異常(checked exception)回滾。

事務使用陷進:http://www.ibm.com/developerworks/cn/java/j-ts1.html
@TransactionalREQUIREDfalseREAD_COMMITTED
相關文章
相關標籤/搜索