【问题标题】:Hibernate over JPA configurtation xml file通过 JPA 配置 xml 文件休眠
【发布时间】:2014-05-22 17:41:36
【问题描述】:
我知道可以通过以下两种方式配置 Hibernate:
hibernate.cfg.xml
-
persistence.xml - JPA - 具有特定的休眠配置
当您像这样添加提供者时:
org.hibernate.ejb.HibernatePersistence
但是,我不明白什么时候应该使用 which ?
正确的行为应该是什么?
谢谢!
【问题讨论】:
标签:
java
xml
hibernate
jakarta-ee
jpa
【解决方案1】:
当您想在项目中使用 Hibernate 时,可以使用 hibernate.cfg.xml。当您创建不同的查询(SELECT、INSERT 等)时,您会打开会话。
Session session = sessions.openSession();
其中 session 是 org.hibernate.Session 的实例。
但正如您所见,我们需要会话来创建会话。 Sessions 是 org.hibernate.SessionSessionFactory 的实例。 SessionFactory 是具体数据库的全局工厂。
可以通过此操作获得会话:
SessionFactory sessions = new Configuration().configure().buildSessionFactory();
new Configuration().configure().buildSessionFactory() 的位置 - 解析 hibernate.cfg.xml
Persistence.xml 包含在项目中使用 JPA 的设置。持久性单元在 persistence.xml 文件中定义,该文件必须位于类路径的 META-INF 目录中。一个 persistence.xml 文件可以包含一个或多个持久性单元的定义。在 JPA 中实例化 EntityManagerFactory 的可移植方式(如 JPA 概述部分所述)需要一个持久性单元。
另请参阅:http://www.objectdb.com/java/jpa/entity/persistence-unit