Hibernate SessionFactory vs. JPA EntityManagerFactory

后端 未结 8 2205
清歌不尽
清歌不尽 2020-11-27 09:03

I am new to Hibernate and I\'m not sure whether to use a Hibernate SessionFactory or a JPA EntityManagerFactory to create a Hibernate Session

相关标签:
8条回答
  • 2020-11-27 09:38

    I want to add on this that you can also get Hibernate's session by calling getDelegate() method from EntityManager.

    ex:

    Session session = (Session) entityManager.getDelegate();
    
    0 讨论(0)
  • 2020-11-27 09:43

    I prefer the JPA2 EntityManager API over SessionFactory, because it feels more modern. One simple example:

    JPA:

    @PersistenceContext
    EntityManager entityManager;
    
    public List<MyEntity> findSomeApples() {
      return entityManager
         .createQuery("from MyEntity where apples=7", MyEntity.class)
         .getResultList();
    }
    

    SessionFactory:

    @Autowired
    SessionFactory sessionFactory;
    
    public List<MyEntity> findSomeApples() {
      Session session = sessionFactory.getCurrentSession();
      List<?> result = session.createQuery("from MyEntity where apples=7")
          .list();
      @SuppressWarnings("unchecked")
      List<MyEntity> resultCasted = (List<MyEntity>) result;
      return resultCasted;
    }
    

    I think it's clear that the first one looks cleaner and is also easier to test because EntityManager can be easily mocked.

    0 讨论(0)
提交回复
热议问题