2012-03-23 46 views
0

使用Spring 3.1,鑽嘴魚科,休眠Spring的事務在JSF

的applicationContext.xml

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> 
    ... 
    </bean>  

    <tx:annotation-driven /> 

    <bean id="transactionManager" 
     class="org.springframework.orm.hibernate3.HibernateTransactionManager"> 
      <property name="sessionFactory" ref="sessionFactory" /> 
    </bean> 

    <context:component-scan base-package="mypackage"/> 

TestBean.java

@Component 
@Scope("session") 
public class TestBean { 

@Autowired private @Getter @Setter HibernateTemplate hibernateTemplate=null; 

public String submit(){ 
    try{ 
     this.test(); 
    }catch (RuntimeException ex) { 
     FacesUtil.addWarn("Error"); 
    } 

    return null; 
} 

@Transactional 
public String test() { 

    Device d1=new Device(); 
    hibernateTemplate.persist(d1); 

    if(1==1) 
     throw new RuntimeException("Testing"); 

    Device d2=new Device(); 
    hibernateTemplate.persist(d2); 
    return null; 
} 

} 

此作品(回滾),但顯示在瀏覽器異常

<h:commandButton value="Submit" action="#{testBean.test}"/> 

試圖表明faces消息,但這種承諾D1

<h:commandButton value="Submit" action="#{testBean.submit}"/> 

調用一些其他bean的(DAO)事務方法太的作品,但我想有代碼託管bean itself.How,我應該JSF處理事務?對於分層架構服務和DAO層,直接處理事務的管理豆

回答

1

上移事務方法又一個層或使用TransactionTemplate如果你希望避免由於某些原因:

public String test() { 
    TransactionTemplate txTemplate = new TransactionTemplate(transactionManager); 

    try { 
     txTemplate.execute(new TransactionCallbackWithoutResult() { 
     @Override 
     protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) { 
      // your transactional code here; 
     } 
     }); 
    } catch (Exception e) { 
     // handle exception here 
    } 
    return null; 
    } 
0

最好去擊敗一類的單一職責原則的目的。

Managed Bean的靈魂目的應該是用於導航處理和網關從視圖層到服務層的數據可以在其中執行主要業務邏輯或使用情況,並委派數據持久化到DAO層。

至於到UI消息而言,你可以趕上從服務層異常,並相應地填充所需的信息。

這樣的事情更易於管理和維護和測試。模擬你的服務層,測試DAO的數據持久性和託管Bean的視圖層。

Spring使用代理/ AOP來實現神奇的@Transactional,並且它更好地接口代碼,因爲如果你不用代碼接口,即直接代理接口或注入的CGLIB子類,它就有它自己的問題。在文檔中查看代理設置的標籤,以便更好地理解代碼的界面。

注:HibernateTemplate的被認爲是一個反面模式和從休眠取出4只支持一個指針,這樣可以在基於Hibernate 3

希望這有助於採取相應的行動!!!!!