使用 Hibernate 4 生成 SQL DB 创建脚本 [英] Generate an SQL DB creation script with Hibernate 4
本文介绍了使用 Hibernate 4 生成 SQL DB 创建脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们目前使用 Hibernate 3,我们使用 Hibernate Tools 为 DB 模式生成 SQL 脚本.
We are currently using Hibernate 3 and we use Hibernate Tools to generate SQL scripts for the DB schema.
我们使用以下 Ant 任务
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>
我们想切换到 Hibernate 4:我们如何在没有 Hibernate 工具的情况下实现类似的功能?
We would like to switch to Hibernate 4: how can we achieve something similar without Hibernate tools?
推荐答案
可以直接使用SchemaExport 类来生成 DDL 脚本:
You can directly use the SchemaExport class to generate the DDL script :
对于休眠 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 更新:
Update for 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);
这篇关于使用 Hibernate 4 生成 SQL DB 创建脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文