我有与Hibernate的JSF maven项目。项目中有一些DAO类,但我认为它实现失败。
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;
}
}
在每个DAO中,我称之为
Session mySession = HibernateUtil.getSessionFactory().openSession();
然后做交易。
现在我想创建泛型 BaseDAO
类并在其中创建基本CRUD操作。但我需要得到EntityManager
。我怎样才能在我的BaseDao中getEntityManager
?
春天我这样做:
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;
}
但是春节项目怎么做呢?
答案 0 :(得分:0)
使用Hibernates工厂方法:
// 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();
取自docs。