gpt4 book ai didi

java - 使用什么: sql migration or entity setups in Spring/Hibernate?

转载 作者:行者123 更新时间:2023-12-01 17:09:42 25 4
gpt4 key购买 nike

当看到为什么大多数程序员使用基于注释的数据库表约束设置时,我有点困惑。例如

@Column(unique=true, nullable=false)

为什么我们需要这个,如果(据我所知)在实际项目中主要使用 SQL 迁移,那么您可以在表创建中创建此约束,例如 CREATE table... name varchar UNIQUE NOT NULL.

我是否需要以两种方式进行设置,还是用 SQL 就足够了?项目中使用 SQL 迁移(Flyway、Liquibase)的频率如何?

此外,Hibernate 在数据库中创建不可读的约束,否则在 SQL 中创建可理解的约束名称。

最佳答案

您可以选择是否让 Hibernate 管理您的架构。如果是,则将根据注释映射的更改创建或更新数据库模式。

我个人不会让 Hibernate 管理我的数据库架构,因为我想确切地知道架构更改发生了什么。 hibernate documentation还以某种方式建议它:

Although the automatic schema generation is very useful for testing and prototyping purposes, in a production environment, it’s much more flexible to manage the schema using incremental migration scripts.

而Flyway、Liquibase是一种增量迁移脚本工具。

Do I need to setup it in both ways, or is it enough to do in SQL? And how often SQL migrations used(Flyway, Liquibase) in projects?

如果您不使用自动架构生成功能,则无需在 @Column 中指定 unique,它仅在自动架构生成的情况下才有意义。

对于 nullable ,它取决于 hibernate.check_nullability设置。如果打开它并且设置了 @Column(nullable=false) ,Hibernate 将帮助在应用程序级别检查此列不能为空,而不要求数据库检查它。但即使不设置它,数据库约束(假设您在数据库中为其创建非空约束)最终也会检查它并且不允许您保存空值

关于java - 使用什么: sql migration or entity setups in Spring/Hibernate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61437648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com