2011-03-02 74 views
2

這是一個在java中使用hibernate的非常簡單的例子:一個函數,當它被調用時,它會在數據庫中創建一個新的對象。如果一切順利,則更改將立即存儲並可見(無緩存問題)。如果失敗了,應該恢復數據庫,就好像這個函數從未被調用一樣。休眠事務結束示例

public String createObject() { 
    PersistentTransaction t = null; 
    try { 
     t = PersistentManager.instance().getSession().beginTransaction(); 
     Foods f = new Foods(); //Foods is an Hibernate object 
     //set some values on f 
     f.save(); 
     t.commit(); 
     PersistentManager.instance().getSession().clear(); 
     return "everything allright"; 
    } catch (Exception e) { 
     System.out.println("Error while creating object"); 
     e.printStackTrace(); 
     try { 
      t.rollback(); 
      System.out.println("Database restored after the error."); 
     } catch (Exception e1) { 
      System.out.println("Error restoring database!"); 
      e1.printStackTrace(); 
     } 
    } 
    return "there was an error"; 
} 

有什麼錯誤?你會改變/改善任何事情嗎?

回答

1

的節省將通過對話而不是對象,除非你已經注入到會話持久化對象。

有一個最後做一個時段收盤也

finally { 
    //session.close() 
} 

建議:如果這個代碼貼是學習的目的則是罰款,否則我會建議使用Spring來管理這個鍋爐板的東西,只擔心關於保存。

+0

如果被調用的函數在jboss環境中,作爲一個web服務?我是否也應該每次關閉會話? – Hectoret 2011-03-02 12:38:39

+0

http://community.jboss.org/wiki/Sessionsandtransactions – 2011-03-02 12:43:17

3

我看不出有什麼不對您的代碼在這裏。正如@Vinod所提到的,我們依賴像Spring這樣的框架來處理繁瑣的鍋爐代碼。畢竟,您不希望每種可能的DAO方法都存在這樣的代碼。他們使事情難以閱讀和調試。

一種選擇是使用AOP,您可以在您的DAO方法上應用AspectJ的「around」建議來處理事務。如果你對AOP感覺不舒服,那麼如果你不使用像Spring這樣的框架,你可以編寫你自己的鍋爐包裝器。

下面是我製作了這可能給你一個想法的例子: -

// think of this as an anonymous block of code you want to wrap with transaction 
public abstract class CodeBlock { 
    public abstract void execute(); 
} 

// wraps transaction around the CodeBlock 
public class TransactionWrapper { 

    public boolean run(CodeBlock codeBlock) { 
     PersistentTransaction t = null; 
     boolean status = false; 

     try { 
      t = PersistentManager.instance().getSession().beginTransaction(); 

      codeBlock.execute(); 

      t.commit(); 
      status = true; 
     } 
     catch (Exception e) { 
      e.printStackTrace(); 
      try { 
       t.rollback(); 
      } 
      catch (Exception ignored) { 
      } 
     } 
     finally { 
      // close session 
     } 

     return status; 
    } 
} 

然後,您的實際DAO方法是這樣的: -

TransactionWrapper transactionWrapper = new TransactionWrapper(); 

public String createObject() { 
    boolean status = transactionWrapper.run(new CodeBlock() { 
     @Override 
     public void execute() { 
      Foods f = new Foods(); 
      f.save(); 
     } 
    }); 

    return status ? "everything allright" : "there was an error"; 
}