我知道可以通过以下两种方式配置 Hibernate:
hibernate.cfg.xml
persistence.xml - JPA - 具有特定的 hibenate 配置 当您像这样添加提供者时:
org.hibernate.ejb.HibernatePersistence
但是,我不明白什么时候应该使用哪个? 正确的行为应该是什么? 谢谢!
最佳答案
当您想在项目中使用 Hibernate 时,可以使用 hibernate.cfg.xml。当您创建不同的查询(SELECT、INSERT 等)时,您将打开 session 。
Session session = sessions.openSession();
其中 session 是org.hibernate.Session的实例。 但正如您所看到的,我们需要 session 来创建 session 。 Sessions 是 org.hibernate.SessionSessionFactory 的实例。 SessionFactory 是具体数据库的全局工厂。 可以通过以下操作获取 session :
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
关于java - Hibernate over JPA 配置 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23813779/