使用Hibernate 4生成SQL DB创建脚本

Mat*_*teo 2 ant hibernate

我们目前正在使用Hibernate 3,我们使用Hibernate Tools为数据库模式生成SQL脚本.

我们使用以下Ant任务

<hibernatetool destdir="${target}">
    <jpaconfiguration persistenceunit="@{persistenceUnit}" propertyfile="@{propertyfile}"/>
    <classpath refid="@{classpathid}"/>
    <!-- the file name is relative to $destdir -->
    <hbm2ddl outputfilename="@{output}" format="true" export="false" drop="false"/>
</hibernatetool>
Run Code Online (Sandbox Code Playgroud)

我们想切换到Hibernate 4:如何在没有Hibernate工具的情况下实现类似的东西?

Ken*_*han 14

您可以直接使用SchemaExport类来生成DDL脚本:

    Configuration config = new Configuration();

    Properties properties = new Properties();

    properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
    properties.put("hibernate.connection.url", "jdbc:postgresql://localhost:5432/Test"); 
    properties.put("hibernate.connection.username", "username");
    properties.put("hibernate.connection.password", "password");
    properties.put("hibernate.connection.driver_class", "org.postgresql.Driver");
    properties.put("hibernate.show_sql", "true");
    config.setProperties(properties);

    config.addAnnotatedClass(MyMappedPojo1.class);
    config.addAnnotatedClass(MyMappedPojo2.class);
    ..................

    SchemaExport schemaExport = new SchemaExport(config);
    schemaExport.setDelimiter(";");

    /**Just dump the schema SQLs to the console , but not execute them ***/
    schemaExport.create(true, false);
Run Code Online (Sandbox Code Playgroud)