问题描述
|
Hibernate文档非常清楚地显示了如何使用XML配置Hibernate。
这是这样做的代码片段:
new Configuration().configure(\"catdb.cfg.xml\")
现在,当您拥有一个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);
解决方法
假设您通常使用持久性单元名称查找配置,则可以创建一个
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);
}
}
,如果您将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多么容易。