JPA EntityManagerFactory Vs Hibernate’s SessionFactory

原文链接:http://javabeat.net/jpa-entitymanager-vs-hibernate-sessionfactory/?utm_source=tuicool&utm_medium=referral


If you are using the JPA’s standard specification implementation (Read :Introduction to JPA), then you would use EntityManagerFactory for opening the session. But, if you are using the hibernate implementation, you have hibernate specific SessionFactory for managing the sessions. Here there is lot of confusion between developers like which one is the best approach. Here, there is two opinions are popular:

如果你正在使用JPA的标准规范实现(阅读:介绍JPA),你会用EntityManagerFactory打开一个session。但是,如果您使用的是Hibernate规范,你将用hibernate特有的SessionFactory来管理session。很多开发者对于这二者哪一种是更好的实现很有疑惑,以下两点很普及:

  1. EntityManagerFactory is  the standard implementation, it is the same across all the implementations. If we migrate our ORM for any other provider, there will not be any change in the approach for handling the transaction. In contrast, if you use hibernate’s session factory, it is tied  to hibernate APIs and ca not migrate to new vendor easily.
  2. One dis-advantage of using the standard implementation is that, it is not providing the advanced features. There is not much control provided in the EntityManager APIs. Whereas, hibernate’s SessionFactory has lot of advanced features which can not done in JPA. One such thing is retrieving the ID generator without closing the transaction, batch insert, etc.

  1. EntityManagerFactory 是一组标准,它在别的框架里不会发生改变。如果我们将我们的ORM迁移到其余开发者上,处理事务的方法不会有任何改变。相反的,如果你用hibernate的sessionfactory,它将用hibernate的api并且不能轻易的移植到其余的框架上。
2   使用这个标准的缺点之一是它不提供高级特性。在EntityManager API中不提供太多的控制。然而,hibernate的sessionFactory 有很多在JPA中不能实现的高级特性。比如在不关闭事务的情况下检索ID生成器,批处理插入等等。

Looking into the above points, one has to decide which one is better. There is no hard rule, after all it depends on the developers requirement. Another suggestion is that, we can use entity manger and session factory together. In this approach, entity manage delegates session handling to the hibernate by invoking the unwrap method. Like this:

通过以上两点,我们很难说哪个更好。一切根据需求。我们可以将entity manager和sessionfactory同时使用。用这种方法,entitymanager通过调用unwrap方法来用hibernate的方法来实现

1 Session session = entityManager.unwrap(Session.class);

Using EntityManagerFactory approach allows us to use callback method annotations like @PrePersist, @PostPersist,@PreUpdate with no extra configuration. Using similar callbacks while using SessionFactory will require extra efforts.

EntityManagerFactory允许我们用回到方法的注解比如 @PrePersist, @PostPersist,@PreUpdate而不加额外配置。在sessionFactory中用相似的回调方法需要额外的配置。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值