spring-boot - spring.jpa.generate-ddl与spring.jpa.hibernate.ddl-auto的关系和区别

标签 spring-boot spring-data-jpa

对于使用 Spring Data JPASpring Boot 应用程序 (2.4.1),@Entity 类基于 javax.persistence 注释。 application.properties 存在这两个属性:

  • spring.jpa.generate-ddl
  • spring.jpa.hibernate.ddl-auto

感谢 STS,以下描述可用:

spring.jpa.generate-ddl

spring.jpa.generate-ddl
java.lang.Boolean

Default: false

Whether to initialize the schema on startup.

spring.jpa.hibernate.ddl-auto

spring.jpa.hibernate.ddl-auto
java.lang.String

DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property. 
Defaults to "create-drop" when using an embedded database and no schema manager was detected. 
Otherwise, defaults to "none"
  • 什么时候使用spring.jpa.generate-ddl
  • 什么时候强制使用spring.jpa.generate-ddl 方法?什么场景?

我确实意识到它被忽略并且确实是强制使用 spring.jpa.hibernate.ddl-auto,它用于以下场景:模式是通过 schema.sql 创建的H2 的 文件和 spring.jpa.hibernate.ddl-autonone,在这种情况下 spring.jpa.generate-ddl 完全被忽略

因此:

spring.jpa.generate-ddlspring.jpa.hibernate.ddl-auto 之间有什么关系(如果存在)和区别?

我找到了这些帖子,但不清楚何时强制使用 spring.jpa.generate-ddl

最佳答案

在此Spring Boot Database Initialization您可以在文章中找到对差异的很好解释。

总而言之,它们几乎都用于同一目标。目标是在对实体类进行任何修改后定义应用程序的行为。鉴于此,第一个允许您进行通用选择,而第二个允许您在一系列行为中做出决定。

(为了避免冲突,我只定义其中一个。)

所以:

  1. spring.jpa.generate-ddl – This configuration takes a boolean value to either enable or disable schema initialization.

假设您正在添加/删除实体用户中的一个字段:在这种情况下:

  • true:它会在您运行应用程序时自动更改您的架构
  • false:架构没有变化。如果对不同步的实体/数据库进行某些调用,应用程序将失败。
  1. spring.jpa.hibernate.ddl-auto – This property takes an enum that controls the schema generation in a more controlled way.

这是有趣的部分,根据您的选择还有更多场景:

  • 无:与 generate-ddl 的“false”行为相同
  • 创建:删除最后一个模式并创建一个新模式。它也会丢弃数据,因此请确保不要在产品中使用它。
  • create-drop :与“创建”选项相同,但方案在关闭时被销毁,而不是在您的应用程序的下一次运行时被销毁。
  • 验证:应用检查实体元素和数据库。如果存在不一致,则返回一些异常。
  • 更新:在这里,例如,如果是新列,应用程序不会创建整个表。它将添加新列并创建唯一索引。

文章中的所有内容都得到了解释(更好),并配有适当的图像向您展示!享受吧!

附言

如果您还想找出 spring.jpa.hibernate.ddl-autohibernate.hbm2ddl.auto 之间的区别,请查看其他 link

spring.jpa.hibernate.ddl-auto This is actually a shortcut for the "hibernate.hbm2ddl.auto" property.

关于spring-boot - spring.jpa.generate-ddl与spring.jpa.hibernate.ddl-auto的关系和区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65401999/

相关文章:

java - Spring中是否为每个Bean都创建了一个代理?

java - 将 Spring Security 添加到 Spring Boot 应用程序导致异常

java - 使用 JPA 时如何允许 arrayList 中出现重复项?

database - jpa spring boot - hibernate 插入速度慢

java - 预先注册可调用参数错误

java - 如何手动启动Kafka监听器?

java - Apache Camel ThreadPoolExecutor(InMemorySagaService)RequestContext问题

java - 无法使用 Spring Boot 呈现 JSP

java - JPA 中的多对多查询

java - Jpa存储库 : NoSuchBeanDefinitionException