2011-04-07 61 views
0

我找不出什麼HibernateUtil是... 是不是需要與JPA?HibernateUtil與JPA

我用GWT的JPA,這個實現是否足夠?

import javax.persistence.EntityManagerFactory; 
import javax.persistence.Persistence; 

public final class EMF { 
    private static final EntityManagerFactory emfInstance = 
     Persistence.createEntityManagerFactory("default"); 

    private EMF() {} 

    public static EntityManagerFactory get() { 
     return emfInstance; 
    } 
} 

,並在使用:

public class AccountDao { 

    public static final EntityManager entityManager() { 
    return Emf.get().createEntityManager(); 
    } 



    public void createAccount(Account account) { 

     EntityManager em = entityManager(); 
     EntityTransaction tx = em.getTransaction(); 

     try { 
      tx.begin(); 
      em.persist(account); 
      tx.commit(); 
     } 
     catch (Throwable t) { 
      t.printStackTrace(); 
      tx.rollback(); 
     } 
     finally { 
      em.close(); 
     } 
     } 
    } 

看到這個post (Gilead JPA configuration)請。我還不明白,如何使用HibernateUtil或HibernateJpaUtil或PersistentBeanManager的東西...

+0

用DTO代替它會更好嗎? – 2011-04-07 16:17:01

回答

2

要與GWT使用Gilead公司,首先從

public class MyServiceImpl extends RemoteServiceServlet implements MyService { 
    .... 
} 

改變你的GWT-RPC服務實現爲:

public class MyServiceImpl extends PersistentRemoteService implements MyService { 
    .... 
} 

然後,在這些類的構造函數,調用該方法setBeanManager(beanManager)。按我在other answer中所述執行設置。下面是引用整個代碼片段:

public class MyServiceImpl extends PersistentRemoteService implements MyService { 


    public MyServiceImpl() { 

    EntityManagerFactory emf = EMF.get(); 

    HibernateJpaUtil hibernateJpaUtil = new HibernateJpaUtil(); 
    hibernateJpaUtil.setEntityManagerFactory(emf); 

    PersistentBeanManager persistentBeanManager = 
     GwtConfigurationHelper.initGwtStatelessBeanManager(hibernateJpaUtil); 

    setBeanManager(persistentBeanManager); 
    } 

    // Service methods follow here 

} 

這是足夠的設置 - 基列然後使用bean管理器(和HibernateJpaUtils)在幕後自動,你不必直接與它交互。你所要做的就是確保你的實體擴展net.sf.gilead.pojo.gwt.LightEntity

+0

請舉例說明如何堅持一個實體 – 2011-04-07 21:02:42

+1

@kostas:堅持一個實體在JPA中照常工作。請參閱http://docs.jboss.org/hibernate/core/3.6/quickstart/en-US/html/hibernate-gsg-tutorial-jpa.html。 (當然,你必須在服務器端做到這一點,實現一個GWT-RPC服務方法,該方法接受來自客戶端的一個或多個實體,然後按照解釋的方式持久化)。 – 2011-04-07 22:08:13

2

你的實現是非常充足的。我會把工廠放在servlet上下文中,而不是靜態的。

但請注意這裏重要的事情。如果你純粹在服務器端使用它,上面的代碼將會起作用。

由於您使用的是GWT,因此在客戶端上使用hibernate「stuff」是可能的(儘管我認爲這不合理)。爲此,你需要吉利德,在那裏你需要前面提到的工具。

+0

我不知道如何用JPA配置Gilead。如果我使用Gilead,EMF.java保持不變,或者必須使用HibernateJpaUtil等配置Gilead教程? – 2011-04-07 16:15:02

+0

你可以在服務器端使用該實體管理器,沒有問題。但對於客戶端 - 按照gilead教程。 – Bozho 2011-04-07 16:19:46

+0

我使用RPC將它傳遞給客戶端,但是它無法將集合註釋爲@OneToOne關係進行desirialize。這就是爲什麼我想使用Gilead,但我無法獲得教程的工作。 Iam只是一名學生。感謝您的幫助無論如何:) – 2011-04-07 16:22:25