2016-04-28 2 views
0

私はHibernateでJSF mavenプロジェクトを持っています。プロジェクトにはいくつかのDAOクラスがありますが、実装に失敗していると思います。各DAOでBaseDaoでEntityManagerを取得するにはどうすればいいですか(Maven + JSF + hibernate)

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

私は

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

使用休止状態ファクトリメソッド:docsから撮影

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

+0

このオプションの意味-myPersistenceContext myPersistenceContext.xmlにパスを設定する必要がありますか? – user5620472

+0

残念ですが、パーシスタンスユニットである必要があります。 src/META.INF(またはsrc/main/resources/META-INF)に[persistence.xml](http://docs.oracle.com/cd/E16439_01/doc.1013/e13981/cfgdepds005.htm)を作成する必要があります。 INF、もしあなたがプロジェクトをビルドしていれば)、あなたのバネ設定のようにユニットの名前をつけてください。 – Stefan

関連する問題