0

我不知道 HibernateUtil 是什么...... JPA需要它吗?

我将 JPA 与 GWT 一起使用,这个实现是否足够?

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();
        }
      }
    }

请参阅这篇文章(Gilead JPA 配置)。我还不明白,如何使用 HibernateUtil,或 HibernateJpaUtil,或 PersistentBeanManager 的东西......

4

2 回答 2

2

你的实现已经足够了。我会将工厂放在 servlet 上下文中,而不是让它成为静态的。

但请注意这里很重要的一点。如果您纯粹在服务器端使用上面的代码,它将起作用。

Since you are using GWT, it is possible (although I don't think it is rational) to use hibernate "stuff" on the client-side. For that you'd need gilead, where you will need the forementioned utilities.

于 2011-04-07T16:09:10.297 回答
2

To use Gilead with GWT, first change your GWT-RPC service implementations from

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

into:

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

Then, in the constructor of these classes, call the method setBeanManager(beanManager). Perform the setup as I described in my other answer. Here's the entire code snippet for reference:

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

}

This is sufficient for the setup - Gilead then uses the bean manager (and HibernateJpaUtils) automatically under the covers, you don't have to interact directly with it. All you have to do is to make sure, that your entities extend net.sf.gilead.pojo.gwt.LightEntity.

于 2011-04-07T16:36:10.000 回答