我正在寻找一种方法来为我的 jpa 注释实体创建一个 ddl。我更喜欢纯Java方式。
如果可能的话,最好也生成 drop 语句。
DataNucleus has SchemaTool that can be invoked from java, or from the command line. It does what you require
--Andy (DataNucleus)
将数据库中的数据导出为 sql
使用liquibase开源项目
LiquiBase 是一个开源 (LGPL)、独立于数据库的库,用于跟踪、管理和应用数据库更改。它建立在一个简单的前提之上:所有数据库更改(结构和数据)都以基于 XML 的描述性方式存储并检查到源代码控制中。
为给定的 JPA 实体生成创建和删除脚本
我们使用这段代码来生成 drop 和 create 语句:只需使用所有实体类构造这个类并调用 create/dropTableScript。
如果需要,您可以改用 persitence.xml 和持久性单元名称。说点什么,我也发布代码。
导入 java.util.Collection; 导入 java.util.Properties; 导入 org.hibernate.cfg.AnnotationConfiguration; 导入 org.hibernate.dialect.Dialect; 导入 org.hibernate.ejb.Ejb3Configuration; /** * 根据 JPA/Hibernate 注释的表的 SQL Creator。 * * 采用: * * {@link #createTablesScript()} 创建表创建脚本 * * {@link #dropTablesScript()} 创建表销毁脚本 * */ 公共类 SqlTableCreator { 私有最终 AnnotationConfiguration hibernateConfiguration; 私有最终属性 dialectProps; 公共 SqlTableCreator(最终集合>实体){ 最终 Ejb3Configuration ejb3Configuration = new Ejb3Configuration(); 对于(最终类实体:实体){ ejb3Configuration.addAnnotatedClass(entity); } dialectProps = new Properties(); dialectProps.put("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect"); hibernateConfiguration = ejb3Configuration.getHibernateConfiguration(); } /** * 创建 SQL 脚本以创建所有表。 * * @return 代表 SQL 脚本的 {@link String}。 */ 公共字符串 createTablesScript() { 最终的 StringBuilder 脚本 = new StringBuilder(); final String[] creationScript = hibernateConfiguration.generateSchemaCreationScript(方言 .getDialect(dialectProps)); for (final String string : creationScript) { script.append(string).append(";\n"); } script.append("\ngo\n\n"); 返回 script.toString(); } /** * 创建 SQL 脚本以删除所有表。 * * @return 代表 SQL 脚本的 {@link String}。 */ 公共字符串 dropTablesScript() { 最终的 StringBuilder 脚本 = new StringBuilder(); final String[] creationScript = hibernateConfiguration.generateDropSchemaScript(方言 .getDialect(dialectProps)); for (final String string : creationScript) { script.append(string).append(";\n"); } script.append("\ngo\n\n"); 返回 script.toString(); } }
Hibernate 对此有内置支持。请参阅org.hibernate.tool.hbm2ddl.SchemaExport。
OpenJPA has support for this too. The OpenJPA mapping tool can create a script or create a ddl file. The ddl should work with other JPA implementations (although each vendor has a few quirks).
If you're using OpenJPA as a persistence provider you can configure OpenJPA to create the tables the first time they're needed by adding the SynchronizeMappings property to persistence.xml.
Example :
<persistence-unit name="test">
<!--
. . .
-->
<properties>
<property name="openjpa.jdbc.SynchronizeMappings"
value="buildSchema"/>
</properties>
<!--
. . .
-->
</persistence-unit>
Here's an explaination of how to use the hibernate SchemaExport class to do exactly what you want.
http://jandrewthompson.blogspot.com/2009/10/how-to-generate-ddl-scripts-from.html
Hope this helps.