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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值