如何使用现代 Spring Boot Data JPA 和 Hibernate 设置生成 ddl 创建脚本?

新手上路,请多包涵

目前,我使用默认的 @SpringBootApplication 注释,在 application.properties 中具有以下属性:

 spring.datasource.url=jdbc:mysql://localhost/dbname
spring.datasource.username=X
spring.datasource.password=X
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.naming_strategy=my.package.CustomNamingStrategy

从 JPA 2.1 开始,我应该可以使用 javax.persistence.schema-generation.* 属性,但是在我的 application.properties 中设置它们似乎没有效果。

我见过 这样 的例子,它们连接了一大堆额外的 bean,但它们没有使用 Mysql。无论如何,这样做需要我配置 Spring 现在正在为我处理的许多选项。

我的目标是:

  • 在MYSQL方言中生成模式创建sql脚本
  • 无需数据库连接
  • 在构建目录中输出脚本
  • 生成休眠环境表也将是一个巨大的优势。

我不想:

  • 在实时数据库上创建/删除模式

库版本:

    hibernate          : 4.3.11.FINAL
   spring framework   : 4.2.5.RELEASE
   spring-boot        : 1.3.3.RELEASE
   spring-data-jpa    : 1.10.1.RELEASE   // for  querydsl 4 support
   spring-data-commons: 1.12.1.RELEASE   // for  querydsl 4 support

(使用gradle,而不是maven)

原文由 Casey 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 781
1 个回答

啊,在我发布这个问题之后,弹簧数据文档的一部分引起了我的注意:

73.5 配置 JPA 属性 此外,当创建本地 EntityManagerFactory 时,spring.jpa.properties.* 中的所有属性都作为普通 JPA 属性(去除前缀)传递。

所以,回答我自己的问题:用 spring.jpa.properties 为 javax.persistence 属性添加前缀:

 spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=create.sql

完成此操作后,模式文件会在项目根目录中自动生成。

原文由 Casey 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进