1

I have JSF maven project with Hibernate. There are some DAO classes in project, but it have failed implementation I think.

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            Configuration configuration = new Configuration().configure();
            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
                    applySettings(configuration.getProperties());
            sessionFactory = configuration.buildSessionFactory(builder.build());
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

In each DAO I call this method

Session mySession = HibernateUtil.getSessionFactory().openSession();

And After that doing transactions.

Now I want create generic BaseDAO class and create base CRUD operations in it. But I need get EntityManager. How can I getEntityManager in my BaseDao?

In spring I do it:

public class BaseJpaDao<E> implements BaseDao<E>{
    protected Class<?> entityClass;

    @PersistenceContext(unitName = "mainDataBase")
    private EntityManager entityManager;

    public BaseJpaDao(Class<?> entityClass) {
        this.entityClass = entityClass;
    }

    @Override
    public E persist(E e) {
        entityManager.persist(e);
        return e;
    }

But how do it in not spring project?

Ataur Rahman Munna
  • 3,887
  • 1
  • 23
  • 34
user5620472
  • 2,722
  • 8
  • 44
  • 97

1 Answers1

0

Use Hibernates factory methods:

// Use persistence.xml configuration
EntityManagerFactory emf = Persistence.createEntityManagerFactory("mainDataBase")
EntityManager em = emf.createEntityManager();
// Retrieve an application managed entity manager    
// Work with the EM
em.close();

Taken from the docs.

Stefan
  • 12,108
  • 5
  • 47
  • 66
  • What means this option -myPersistenceContext I need set path to myPersistenceContext.xml? – user5620472 Apr 28 '16 at 04:59
  • I'm sorry, it should be persistence-unit. You should create a [persistence.xml](http://docs.oracle.com/cd/E16439_01/doc.1013/e13981/cfgdepds005.htm) in src/META.INF (or src/main/resources/META-INF, if its a maven project) and name the unit like you did in your spring configuration. – Stefan Apr 28 '16 at 06:04