2

現在Hibernate3を使用しており、HibernateToolsを使用してDBスキーマの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>

Hibernate 4に切り替えたいと思います。Hibernateツールなしで同様のことをどのように達成できますか?

4

1 に答える 1

14

SchemaExportクラスを直接使用して、DDLスクリプトを生成できます。

Hibernate 4の場合:

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

Hibernate 5のアップデート:

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

    StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(properties).build();

    MetadataSources metadataSource = new MetadataSources(serviceRegistry);
    metadataSource.addAnnotatedClass(MyMappedPojo1.class);
    metadataSource.addAnnotatedClass(MyMappedPojo2.class);
    ...........

    Metadata meta = metadataSource.buildMetadata();

    SchemaExport schemaExport = new SchemaExport();
    schemaExport.setDelimiter(";");
    schemaExport.execute(EnumSet.of(TargetType.STDOUT), Action.CREATE, meta);
于 2012-12-24T05:35:48.863 に答える