【问题标题】:Spring JPA Hibernate ddl-auto does not detects auto increment constraint changeSpring JPA Hibernate ddl-auto 未检测到自动增量约束更改
【发布时间】:2021-05-23 11:05:08
【问题描述】:

我用 User 实体创建了一个简单的 SpringBoot 应用程序,定义如下:

@Entity
public class User {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
}

我发现添加@GenerateValue注解并没有给主键添加auto_increment属性。 SQL 工作台对id 的约束是id: bigint PK

后来发现auto_increment可以通过将@GenerateValue注解替换为@GeneratedValue(strategy = GenerationType.IDENTITY)来添加到key中。

我做了这个更改并重新运行了 Spring Boot 服务器,发现没有对主键进行任何更改,即没有添加 auto_increment。我的 ddl-auto 属性是 spring.jpa.hibernate.ddl-auto=update

然后我将ddl-auto属性更新为create,它先删除表,然后创建一个新表,发现新表的主键具有auto_increment属性。工作台中更新的约束为id: bigint AI PK

后来,我还尝试了ddl-autovalidate 属性,看看hibernate 是否可以使架构约束不匹配无效,但它无法这样做。

有人可以解释一下这种行为的原因吗?显然,未在主键中设置的 auto_increment 属性必须符合架构不匹配的条件,并且应该由 validate 无效并由 update ddl-auto 值更新。

谢谢。

【问题讨论】:

  • 忠告:不要将 Hibernate 的 DDL 生成用于生产。使用数据库迁移工具

标签: mysql spring-boot hibernate jpa


【解决方案1】:

Hibernate 可能忽略了验证中的自动增量,因为架构是代表您的数据库结构的东西,例如表、列、列类型、大小、表映射等。当有插入表时,自动增量就会出现。这只是生成不影响结构的列值之一的方式。

【讨论】:

    猜你喜欢
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 2015-06-19
    • 2011-06-08
    • 2011-03-18
    • 1970-01-01
    • 2018-04-25
    相关资源
    最近更新 更多