欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

使用Hibernate 4,JPA和Maven的架构创建脚本

发布时间:2023/12/3 38 豆豆
生活随笔 收集整理的这篇文章主要介绍了 使用Hibernate 4,JPA和Maven的架构创建脚本 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
这种情况很简单–您想要在构建应用程序时生成数据库模式创建脚本(然后在目标数据库上执行脚本),这对于Hibernate 3来说相对容易,因为有 hibernate3-maven-plugin ,但是与Hibernate 4不兼容。当然,对于每个新项目,都应从Hibernate 4开始。 那么该怎么办? 它相对简单,但是需要花费一些时间进行研究和测试。 这个想法是使用SchemaExport工具。 但这有点棘手,因为它仅支持本地Hibernate配置,而不支持JPA。

首先,创建一个处理导出的命令行应用程序。 请注意,不建议使用Ejb3Configuration,但不建议将其用于外部使用-休眠在内部大量使用了它。 因此,这是一个正常的工作类:

@SuppressWarnings('deprecation') public class JpaSchemaExport {public static void main(String[] args) throws IOException {execute(args[0], args[1], Boolean.parseBoolean(args[2]), Boolean.parseBoolean(args[3]));}public static void execute(String persistenceUnitName, String destination, boolean create, boolean format) {System.out.println('Starting schema export');Ejb3Configuration cfg = new Ejb3Configuration().configure(persistenceUnitName, new Properties());Configuration hbmcfg = cfg.getHibernateConfiguration();SchemaExport schemaExport = new SchemaExport(hbmcfg);schemaExport.setOutputFile(destination);schemaExport.setFormat(format);schemaExport.execute(true, false, false, create);System.out.println('Schema exported to ' + destination);} }

请注意,我们没有将文件直接部署到目标数据库。 (.execute的第二个参数为false)。 这是因为在persistence.xml中没有数据库连接属性-它们是外部的。 稍后在maven构建中完成架构文件的部署,但这超出了本文的范围。

然后,我们只需要从Maven构建中调用此类。 我最初尝试将其创建为ant任务,并使用antrun插件运行它,但是它存在类路径和类加载器问题(找不到实体和persistence.xml)。 这就是为什么我使用exec-maven-plugin的原因,该插件在运行构建的同一JVM中调用该应用程序:

<plugin><groupId>org.codehaus.mojo</groupId><artifactId>exec-maven-plugin</artifactId><version>1.1</version><executions><execution><phase>${sql.generation.phase}</phase> <!-- this is process-classes in our case currently --><goals><goal>java</goal></goals></execution></executions><configuration><mainClass>com.yourcompany.util.JpaSchemaExport</mainClass><arguments><argument>core</argument><argument>${project.build.directory}/classes/schema.sql</argument><argument>true</argument><argument>true</argument></arguments></configuration> </plugin>

然后,您可以使用sql-maven-plugin将schema.sql文件部署到目标数据库(您将需要使maven加载外部化的db属性,这由properties-maven-plugin完成)。

参考: 如何从Bozho的技术博客博客的JCG合作伙伴 Bozhidar Bozhanov 使用Hibernate 4,JPA和Maven生成模式创建脚本 。


翻译自: https://www.javacodegeeks.com/2012/07/schema-creation-script-with-hibernate-4.html

总结

以上是生活随笔为你收集整理的使用Hibernate 4,JPA和Maven的架构创建脚本的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。