【问题标题】:How do I configure Hibernate with a JPA 2.0 file?如何使用 JPA 2.0 文件配置 Hibernate?
【发布时间】:2011-05-24 14:19:49
【问题描述】:

Hibernate 文档非常清楚地显示 how to configure Hibernate with XML

这是执行此操作的代码的 sn-p:

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);

【问题讨论】:

    标签: hibernate jpa persistence


    【解决方案1】:

    假设您通常使用持久性单元名称查找配置,您可以创建一个 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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      如果您将 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 是多么容易。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-11
        • 2020-03-16
        • 1970-01-01
        • 2011-02-09
        • 2013-03-19
        • 2018-06-02
        • 1970-01-01
        相关资源
        最近更新 更多