您的位置:首页 > 编程语言 > Java开发

JPA EntityManagerFactory Vs Hibernate’s SessionFactory

2017-03-16 20:24 513 查看
原文链接: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。很多开发者对于这二者哪一种是更好的实现很有疑惑,以下两点很普及:

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

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中用相似的回调方法需要额外的配置。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐