Search code examples
javahibernategwtjpagilead

HibernateUtil with JPA


I can't figure out what HibernateUtil is ... Is it required with JPA?

I use JPA with GWT , is this implementation sufficient?

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

And at the use:

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

See this post (Gilead JPA configuration) please. I can't understand yet, how to use HibernateUtil, or HibernateJpaUtil, or PersistentBeanManager stuff ...


Solution

  • 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.