我知道可以通过以下两种方式配置Hibernate:
-
hibernate.cfg.xml
-
persistence.xml - JPA -具有特定的hibernate配置当您像这样添加提供程序时:
org.hibernate.ejb.HibernatePersistence
但是,我不明白什么时候该用哪个?正确的行为应该是什么?谢谢!
当您想在项目中使用Hibernate时,可以使用Hibernate .cfg.xml。当您创建不同的查询(SELECT, INSERT等)时,您打开会话。
Session session = sessions.openSession();
where session是的实例。org.hibernate.Session但正如你所看到的,我们需要会话来创建会话。Sessions是org.hibernate.SessionSessionFactory的实例。SessionFactory是具体数据库的全局工厂。会话可以通过以下动作获得:
SessionFactory sessions = new Configuration().configure().buildSessionFactory();
where new Configuration().configure().buildSessionFactory()
- parses hibernate.cfg.xml
Persistence.xml包含在您的项目中使用JPA的设置。持久化单元在 Persistence .xml文件中定义,该文件必须位于类路径中的META-INF目录中。一个persistence.xml文件可以包含一个或多个持久化单元的定义。在JPA中实例化EntityManagerFactory
的可移植方法(如JPA概述部分所述)需要一个持久化单元。
参见:http://www.objectdb.com/java/jpa/entity/persistence-unit