【问题标题】:Hibernate: Generate the DDl to a output file using the update="true" and outputfilename in hbm2ddl toolHibernate:使用 hbm2ddl 工具中的 update="true" 和 outputfilename 将 DDl 生成到输出文件
【发布时间】:2011-10-07 23:25:14
【问题描述】:

我正在尝试将生成的 DDL 导出到输出文件,而不是直接在命令提示符中显示 hbm2ddl.auto=update(使用自动模式生成)。

我知道使用它为生产数据库生成架构可能不是一个好主意。我已经浏览了讨论它的线程。

Hibernate: hbm2ddl.auto=update in production?

我正在尝试将其用于开发/测试数据库。

但是,我在这里面临的挑战是它没有将生成的 DDL 发送到输出文件,即使我在 hbm2ddl 中使用“输出文件名”属性
出口商。 (根据这个http://docs.jboss.org/tools/2.1.0.Beta1/hibernatetools/html/ant.html

这是我的 build.xml 的样子。我正在使用 Hibernate 的 Jpa 配置。

<taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask"     classpathref="classpath.hibernate" />

<target name="db_update_schema_sql" depends="db_config"
        description="create SQL script for updating schema">
    <hibernatetool destdir="${out.dir}">
       <jpaconfiguration persistenceunit="${persistence.unit.name}"/>
       <classpath path="${build.classes.dir}"/>             
       <hbm2ddl export="false" create="false" update="true" drop="false"     outputfilename="update.sql" delimiter=";" format="true"/>          
    </hibernatetool>
</target>

<target name="db_full_update" depends="db_config" description="Updates database">
    <antcall target="db_update_schema_sql" />
</target>

当我设置 update="true" 时,永远不会创建/更新“update.sql”。它仅在我使用 create="true" 或 drop="true" 或两者时创建/更新。

我对此进行了一些研究。我在 Hibernate Jira 中发现了一些与此相关的问题。它仍然说它没有解决。有一个可用的补丁。不确定
是否有人使用过这个补丁。

https://hibernate.onjira.com/browse/HHH-1186 https://hibernate.onjira.com/browse/HBX-757

如果有人使用此 update="true" 功能将 ddl 直接生成到文件中,向我解释他们是如何做到的,我将不胜感激。

另外,如果您为此使用补丁,能否告诉我您是如何将补丁应用到现有 Jar 文件的。

谢谢, SM

【问题讨论】:

    标签: hibernate


    【解决方案1】:

    直接使用相关类即可。

    Connection connection = DriverManager.getConnection( dbUrl, dbUsername, dbPassword );
    connection.setSchema (dbSchema);
    Dialect dialect = ...; // eg, new MySQL5InnoDBDialect();
    DatabaseMetadata metadata = new DatabaseMetadata( connection, dialect, null );
    
    Configuration cfg = new Configuration();
    cfg.addAnnotatedClass(...); // or read from xml
    cfg.buildMappings();
    List<SchemaUpdateScript> updateScritps = cfg.generateSchemaUpdateScriptList( dialect, metadata );
    
    for ( SchemaUpdateScript script : updateScritps ) 
    {
        String formatted = FormatStyle.DDL.getFormatter().format (script.getScript());
    
        // Replace with writing to file:
        System.out.println( formatted + ";" );
    }
    

    程序员的本意是编程,而不是与 XML 搏斗。

    另请查看org.hibernate.tool.hbm2ddl.SchemaUpdate的源代码。

    【讨论】:

      猜你喜欢
      • 2015-06-20
      • 1970-01-01
      • 2016-02-15
      • 2012-04-09
      • 2011-02-24
      • 2012-08-23
      • 2015-11-12
      • 2012-05-13
      • 2010-09-21
      相关资源
      最近更新 更多