2011-05-24 50 views
2

休眠文档显示非常清晰how to configure Hibernate with XML如何使用JPA 2.0文件配置Hibernate?

这是代码段的可以这样做:

new Configuration().configure("catdb.cfg.xml") 

现在,你如何配置Hibernate Hibernate配置文件,而不是时,你有一个JPA 2.0配置文件?

  • 如何为META-INF/persistence.xml做到这一点?
  • 如果我的文件名为META-INF/jpa.xml,该怎么办?

这是用于Hibernate 3.6和JPA 2.0的。我的最终目标是能够为文件persistence.xml中描述的类导出模式DDL,所以我不想构建SessionFactory。

Configuration cfg = /* ??? */ 

    SchemaExport schemaExport = new SchemaExport(cfg); 
    schemaExport.setDelimiter(";"); 
    schemaExport.setOutputFile("ddl.sql"); 
    boolean script = true, export = false, justDrop = false, justCreate = false; 
    schemaExport.execute(script, export, justDrop, justCreate); 

回答

0

如果使用JPA 2.0与Hibernate,你唯一需要的文件是一个位于META-INF目录中的persistence.xml文件。

如何配置persistence.xml文件是一个广泛的主题,具体取决于您正在构建的应用程序的类型。

举例来说,我目前正在运行使用Hibernate 3.6.2,其唯一的配置文件的应用程序是persistence.xml并只具有以下行

<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> 
    <persistence-unit name="xyz" transaction-type="RESOURCE_LOCAL"/> 
</persistence> 

这就是我所需要的。在运行时,当我启动实体管理器工厂时,我提供了更多的属性,但我打算演示的是,使用Hibernate配置JPA是多么容易。

4

假设你使用一个持久性单元名称通常查找您的配置,您可以创建一个org.hibernate.ejb.Ejb3Configuration,并得到它的返回所包装的org.hibernate.cfg.Configuration

package test; 

import org.hibernate.cfg.Configuration; 
import org.hibernate.ejb.Ejb3Configuration; 
import org.hibernate.tool.hbm2ddl.SchemaExport; 

public class SchemaExportTest { 
    public static void main(String[] args) { 
     Configuration cfg = new Ejb3Configuration().configure("persistence-unit-name", null).getHibernateConfiguration(); 

     SchemaExport export = new SchemaExport(cfg); 

     export.execute(true, false, false, false); 
    } 
} 
相关问题