【发布时间】: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-auto 的validate 属性,看看hibernate 是否可以使架构约束不匹配无效,但它无法这样做。
有人可以解释一下这种行为的原因吗?显然,未在主键中设置的 auto_increment 属性必须符合架构不匹配的条件,并且应该由 validate 无效并由 update ddl-auto 值更新。
谢谢。
【问题讨论】:
-
忠告:不要将 Hibernate 的 DDL 生成用于生产。使用数据库迁移工具
标签: mysql spring-boot hibernate jpa