JPA EntityManagerFactory Vs Hibernate' SessionFactory

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:
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.
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:
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.
译: 如果您正在使用JPA的标准规范实现(请阅读:JPA简介),那么您将使用EntityManagerFactory打开会话。但是,如果您使用的是hibernate实现,那么您有用于管理会话的特定的SessionFactory。这里开发者之间有很多混淆,比如哪一个是最好的方法。这里有两个意见是流行的:
1.EntityManagerFactory是标准的实现,在所有的实现中都是一样的。如果我们将ORM迁移到任何其他提供者,那么处理交易的方法将不会有任何改变。相比之下,如果您使用hibernate的会话工厂,则会绑定到休眠API,并且不会轻易迁移到新的供应商。
2.使用标准实现的一个不利之处是,它没有提供高级功能。EntityManager API中没有提供太多的控制。而Hibernate的SessionFactory有许多先进的特性,这些特性在JPA中是无法做到的。一个这样的事情是检索ID生成器,而不关闭交易,批量插入等。
考虑到以上几点,我们必须决定哪一个更好。没有硬性规定,毕竟取决于开发者的要求。另一个建议是,我们可以一起使用实体经理和会话工厂。在这种方法中,实体通过调用unwrap方法管理委托会话处理到休眠状态。喜欢这个:
Session session = entityManager.unwrap(Session.class);

使用EntityManagerFactory方法允许我们使用像@PrePersist,@ PostPersist,@ PreUpdate这样的回调方法注释,而不需要额外的配置。在使用SessionFactory时使用类似的回调将需要额外的努力。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值