我正在开发一个使用 Hibernate 4.1、Spring 3.1 和 JPA 2.0 的项目,我想验证我从互联网上收集到的信息是否正确。
我正在尝试决定是使用 JPA entityManager 还是使用特定于 hibernate 的 sessionFactory。
起初我计划使用 entityManager 和完整的 JPA 规范,因此我的项目将与 Hibernate 解耦,如果后来有什么想法让我信服,我可以把它换成其他东西,比如 EclipseLink。
然而,entityManager 似乎有一些非常重要的限制。
我的问题:
我想要使用完整的 JPA 规范和 entityManager 的唯一原因是能够相对轻松地为不同的 JPA 2.0 兼容 ORM 切换 Hibernate,对吗?使用 entityManager 真的没有性能/功能/易于编程的好处吗?
其次,hibernate sessionFactory 似乎比 entityManager 有很多好处。到目前为止,我遇到了 entityManager 无法执行实体列表的批量插入的问题,我读过 sessionFactory 可以。我还读到 sessionFactory 可以自动返回自动生成的实体 ID,而使用 entityManager 您需要结束事务/刷新持久性上下文以提取新生成的 ID。
我喜欢我的项目与 Hibernate 相对分离的想法,但我更希望能够从一开始就编写高效的数据库更新。所以我应该切换到为 hibernate 和 sessionFactory 配置的项目,对吗?
最佳答案
我会坚持使用 JPA2,就像你会使用 List
而不是 ArrayList
:你更喜欢接口(interface)(或抽象)而不是实现。除了 HQL 知道比 JPQL 或外来特性“更多”的东西之外,没有太大区别。还要记住 JPA 是在 Hibernate 之后制作的,而 Hibernate 是 JPA 背后的“灵感”。
对于奇异的特性:Hibernate Entity Manager 包装一个 Hibernate Session。如果您真的需要它们,您可以将 EntityManager
转换为 Hibernate 接口(interface) (org.hibernate.jpa.HibernateEntityManager
),然后使用该 session 。但如果我说我试过了,那我就是在骗你。
我还评论了你的部分问题:
The only reason I would want to use full JPA specifications and the entityManager is to be able to switch out Hibernate for a different JPA 2.0 compatible ORM relatively easily, right? Are there really no performance / functionality / ease of programming benefits to using the entityManager?
从 Hibernate 切换到 EclipseLink 并不意味着您“只需要交换 jar”。映射和注释解析不一样,您会遇到可能会阻止您切换的问题。
您可以阅读 my question here举一个我在使用两者时遇到的问题的例子(这是一个 maven 项目,其配置文件将 JPA2.1 impl 从 EclipseLink 切换到 Hibernate)。我放弃了 EclipseLink,因为我无法像我想要的那样命名数据库对象(或者更确切地说,指定数据库对象的名称)。
Second, it seems like the hibernate sessionFactory has a lot of benefits over the entityManager. So far I've run into the issue that the entityManager can't perform a batch insert of a list of entities, which I've read the sessionFactory can. I've also read that the sessionFactory can return an auto-generated entity ID automatically, while with the entityManager you need to end the transaction / flush the persistence context to pull the newly generated id.
这取决于您如何生成实体 ID。但是想一想:在持久化上下文需要持久化它之前,您的实体不会持久化。这就是你没有身份证的原因。刷新它,也就是发送带有生成 id 的插入查询,是唯一的方法。
这同样适用于 session 工厂。
不过,您也许可以从 Hibernate 访问序列生成器,但您也可以在原生 SQL 中使用 EntityManager
来实现。
I liked the idea of my project being relatively decoupled from Hibernate, but I would much rather be able to write efficient database updates from the get-go. So I should switch over to my project being configured for hibernate and the sessionFactory, right?
您可以将其视为针对 ORM 的巨魔,但为了有效地更新数据库,请使用普通 JDBC(或 Spring Jdbc 模板)。至少您会知道数据何时会更新,并且您将能够更好地优化(批量更新等)。
关于java - 使用 hibernate sessionFactory 或 JPA entityManager?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14599216/