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


但是在春季项目中如何做呢?

最佳答案

使用休眠的工厂方法:

// 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

08-27 05:29