Hibernate 和 SQLite:在创建时设置唯一约束

Hibernate and SQLite : Set unique constraint on creation

我正在使用 Hibernate 创建 SQLite tables.

我有一个table这样的

@Entity 
class Person(

    @Column(unique = true, nullable = false)
    val name: String,

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Int? = null,
)

我看到在创建数据库时,稍后通过 ALTER 请求添加了 unique 约束

Hibernate: create table Person (id  integer, name varchar(255) not null, primary key (id))
Hibernate: alter table Person add constraint UK_is4vd0f6kw9sw4dxyie5cy9fa unique (name)

除了 SQLite does not seem to support ALTER requests modifying constraints on tables.

所以我的问题是:有没有一种方法可以直接指示 Hibernate 在 table 创建时设置唯一性约束?最好的方法是什么?

以后我可以通过代码轻松确保唯一性,但如果可以的话,我宁愿使用数据库的强大功能。

我应该补充一点,到目前为止,我正在为 hibernate.hbm2ddl.auto 使用 update 设置,因此 Hibernate 会自行生成 SQL。我对其他方法持开放态度,但如果可以减少维护,我宁愿避免使用它们。

我会回答我自己的问题,因为它没有得到太多关注:)。

SQLite 确实不支持带约束的 ALTER,并且 Hibernate(据我所知)不提供使用自定义 SQL 的简洁方法。 除此之外,it is not recommended to use Hibernate: hbm2ddl.auto=update in production.

出于这些原因,我决定将自己变成 Flyway 并编写自己的 SQL。好消息是添加 Flyway 提供了我的数据库迁移。坏消息是它又需要维护一个依赖项。

我做了什么:

在我的 build.gradle.kts

中添加了 flyway 依赖项
    implementation("org.flywaydb:flyway-core:8.4.3")

在我的代码中休眠之前实例化了 flyway,指向同一个数据库:

    val flyway = Flyway
        .configure()
        .dataSource("jdbc:sqlite:test.db", null, null).load()
    flyway.migrate()

resources/V1__Create_person_and_entries_table.sql

中添加了一个手写的 SQL 迁移文件
create table Person
(
    id   integer primary key,
    name varchar(255) not null UNIQUE
);

瞧瞧!

我在 here 上写了一篇博客 post,其中包含更多详细信息以及使用 Flyway 之类的更多理由。