2010-11-19 40 views
0

我正在開始使用Hibernate,並嘗試從Web應用程序中將一些數據保存到我的數據庫中。無法通過休眠來保存我的數據

我的servlet代碼是在這裏:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    PrintWriter pr = response.getWriter(); 
    ServletContext ctx = super.getServletContext(); 
    try { 
     EntityManagerFactory emf = Persistence.createEntityManagerFactory("agricultural-register-server"); 
     EntityManager em = emf.createEntityManager(); 
     em.joinTransaction(); 
     VolumeType vt = new VolumeType(1, "asd"); 
     Volume v = new Volume("a", "b", "c", 123123, vt, 1); 
     em.persist(vt); 
     em.persist(v); 
     em.flush(); 
     em.close(); 
     RequestDispatcher dispatcher = ctx.getRequestDispatcher("/index.jsp"); 
     dispatcher.forward(request, response); 
    } catch (Exception e) { 
     pr.println("Error occured while testing"); 
     e.printStackTrace(); 
    } 
} 

我的問題是,它給我的錯誤:

javax.persistence.TransactionRequiredException:沒有交易正在進行

我已將persistence.xml中的選項放入:

<屬性名= 「hibernate.hbm2ddl.auto」 值= 「創造」/>

,它創造好我的表。所以我認爲我的問題是我需要使我的代碼事務。但我該怎麼做?

如果我嘗試這樣做:

em.getTransaction(); //.... 

提示錯誤(我想是因爲我說過我是交易型作爲我的persistence.xml「JTA」)。

那麼,有人可以幫助我嗎?

在此先感謝。


我解決我的問題,通過這樣做:在這個環節發現

Context ic = new InitialContext(); 
UserTransaction ut = (UserTransaction)ic.lookup("java:comp/UserTransaction"); 
ut.begin(); 
//...transactional code 

ut.commit(); 

幫助:http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/transactions/transactions6.html

但不管怎麼說,這方面的一些toughts將是開山鼻祖。

回答

0

你試過了嗎?

em.beginTransaction(); 

最後,您將需要提交或回滾您的交易與尊重的方法的幫助。

+0

它給了我錯誤,因爲我在我的persistence.xml文件中指定了JTA事務類型。 (我認爲這就是我不能使用交易的原因。) – artaxerxe 2010-11-19 20:17:54