Generate an SQL DB creation script with Hibernate

2019-01-23 00:34发布

问题:

We are currently using Hibernate 3 and we use Hibernate Tools to generate SQL scripts for the DB schema.

We use the following Ant task

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

We would like to switch to Hibernate 4: how can we achieve something similar without Hibernate tools?

回答1:

You can directly use the SchemaExport class to generate the DDL script :

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 ant