使用Hibernate 4生成SQL数据库创建脚本

3

我们目前使用的是Hibernate 3,我们使用Hibernate工具生成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工具,我们该如何实现类似的功能?

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接