Java交易管理之Spring+Hibernate__Java

來源:互聯網
上載者:User
環境與版本

除了上一篇中的hibernate的相關lib 外

  Java交易管理之Hibernate


還需要加入Spring的lib 包和如下的一些依賴包

org.aopalliance
org.aspectj
org.apache.commons


Spring 的版本是Spring 4.1.5。

依賴包也可以到Spring 官方網站下載到 ,名字類似 spring-framework-3.0.2.RELEASE-dependencies


理論知識

Spring和Hibernate整合後,通過Hibernate API進行資料庫操作時發現每次都要opensession,close,beginTransaction,commit,這些都是重複的工作,我們可以把交易管理部分交給spring架構完成。


使用spring管理事務後在dao中不再需要調用beginTransaction和commit,也不需要調用session.close(),使用API  sessionFactory.getCurrentSession()來替代sessionFactory.openSession()



* 如果使用的是本地事務(jdbc事務)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全域事務(jta事務)
<property name="hibernate.current_session_context_class">jta</property>



Spring中Propagation類的事務屬性詳解:
PROPAGATION_REQUIRED:支援當前事務,如果當前沒有事務,就建立一個事務。這是最常見的選擇。 
PROPAGATION_SUPPORTS:支援當前事務,如果當前沒有事務,就以非事務方式執行。 
PROPAGATION_MANDATORY:支援當前事務,如果當前沒有事務,就拋出異常。 
PROPAGATION_REQUIRES_NEW:建立事務,如果當前存在事務,把當前事務掛起。
PROPAGATION_NOT_SUPPORTED:以非事務方式執行操作,如果當前存在事務,就把當前事務掛起。 
PROPAGATION_NEVER:以非事務方式執行,如果當前存在事務,則拋出異常。 
PROPAGATION_NESTED:支援當前事務,如果當前事務存在,則執行一個嵌套事務,如果當前沒有事務,就建立一個事務。


Spring 可以使用xml方式進行配置或是使用註解聲明的方式進行事務的管理。 xml 方式配置事務代碼執行個體

代碼結構如下:


applicationContext.xml

<?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:context="http://www.springframework.org/schema/context"xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="        http://www.springframework.org/schema/util        http://www.springframework.org/schema/util/spring-util-3.1.xsd        http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd        http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.1.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd       http://www.springframework.org/schema/tx     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd    http://www.springframework.org/schema/aop    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><context:component-scan base-package="com.oscar999.trans.sprhib" /><context:property-placeholder location="classpath:/com/oscar999/trans/sprhib/config.properties" /><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"><!-- Connection Info --><property name="driverClassName" value="${jdbc.driver}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}"></property></bean><bean id="sessionFactory"class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop><prop key="hibernate.hbm2ddl.auto">update</prop><prop key="hibernate.show_sql">true</prop><prop key="hibernate.format_sql">true</prop><prop key="hibernate.jdbc.batch_size">20</prop><prop key="hibernate.enable_lazy_load_no_trans">true</prop><prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop><prop key="jdbc.use_streams_for_binary">true</prop></props></property><property name="packagesToScan"><list><value>com.oscar999.trans.sprhib.model</value></list></property></bean><!-- Transaction --><bean id="transactionManager"class="org.springframework.orm.hibernate4.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory" /></bean><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="save*" propagation="REQUIRED" /><tx:method name="*" read-only="true" /></tx:attributes></tx:advice><aop:config proxy-target-class="true"><aop:pointcut expression="execution(* com.oscar999.trans.sprhib.dao.ProductDAOImpl.*(..))" id="pointcut" /><aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" /></aop:config></beans>

config.properties

jdbc.driver=oracle.jdbc.driver.OracleDriverjdbc.url=jdbc:oracle:thin:@12.6.18.43:1521:orcljdbc.username=jdbc.password=oracle


Product.java

/**    * @Title: Product.java * @Package com.oscar999.trans.hibernate * @Description: * @author XM * @date Feb 15, 2017 1:44:47 PM * @version V1.0    */package com.oscar999.trans.sprhib.model;import java.io.Serializable;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.Table;/** * @author XM *  */@Entity@Table(name = "TEST_PRODUCT")public class Product implements Serializable {public Product() {}@Id@Column(name = "ID")private Integer id;@Column(name = "NAME")private String name;@Column(name = "PRICE")private String price;private static final long serialVersionUID = 1L;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPrice() {return price;}public void setPrice(String price) {this.price = price;}}

ProductDAOImpl.java

/**    * @Title: ProductDAOImpl.java * @Package com.oscar999.trans.sprhib * @Description:  * @author XM * @date Feb 15, 2017 4:15:09 PM * @version V1.0    */package com.oscar999.trans.sprhib.dao;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;import com.oscar999.trans.sprhib.model.Product;/** * @author XM *  */@Repositorypublic class ProductDAOImpl {@Autowiredprivate SessionFactory sessionFactory; public Product findProductById(int id) {Session session = sessionFactory.getCurrentSession();Product product = (Product) session.get(Product.class, id);return product;}public Product saveProduct(Product product) {Session session = sessionFactory.getCurrentSession();session.save(product);return product;}}


ProductServiceImpl.java

package com.oscar999.trans.sprhib;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.oscar999.trans.sprhib.dao.ProductDAOImpl;import com.oscar999.trans.sprhib.model.Product;@Servicepublic class ProductServiceImpl {@Autowiredprivate ProductDAOImpl productdao;public void findProduct(int id) {Product product = productdao.findProductById(id);if (product != null) {System.out.println(product.getName());}}public void saveProduct() {Product product = new Product();product.setId(2);product.setName("product2");product.setPrice("price2");productdao.saveProduct(product);}}


TestMain.java

/**    * @Title: TestMain.java * @Package com.oscar999.trans.sprhib * @Description:  * @author XM * @date Feb 15, 2017 3:54:54 PM * @version V1.0    */package com.oscar999.trans.sprhib;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * @author XM *  */public class TestMain {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/oscar999/trans/sprhib/applicationContext.xml");ProductServiceImpl productService = applicationContext.getBean(ProductServiceImpl.class);//productService.findProduct(1);productService.saveProduct();}}

說明如下:

get 可以不需要transaction
插入或是更新如果沒有的話, 就不會更新成功


聲明方式配置事務
需要在xml配製中設定<tx:annotation-driven transaction-manager="transactionManager"> 
事物註解方式: @Transactional
當標於類前時,標示類中所有方法都進行事物處理,以下代碼在service層進行交易處理(給Service層配置事務是比較好的方式,因為一個Service層方法操作可以關聯到多個DAO的操作。在Service層執行這些Dao操作,多DAO操作有失敗全部復原,成功則全部提交。)


@Service


 @Transactional


 public class UserServiceImpl implements UserService {


     @Autowired


      private UserDao userDao;


 
     public User getUserById(int id) {


          return userDao.findUserById(id);


      }


 }




當類中某些方法不需要事物時:
@Service


  @Transactional


 public class UserServiceImpl implements UserService {


     @Autowired


     private UserDao userDao;


 
     @Transactional(propagation = Propagation.NOT_SUPPORTED)


     public User getUserById(int id) {


         return userDao.findUserById(id);


     }


 }



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.