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?