如何让hibernate创建复杂的唯一约束?

问题描述 投票:0回答:1

我正在使用

hibernate
自动生成我的表格。 现在我想添加一个相当复杂的唯一约束,如下所示:

UNIQUE KEY person_unique ((coalesce(firstname, 'null')), (coalesce(lastname, 'null')), (coalesce(dob, 'null')));

@Entity
public class Person {
   @Id long id;

   @Column(nullable=true)
   String firstname, lastname;

   @Column(nullable=true)
   LocalDate dob;
}

我想使用约束来防止插入也遵循空值字段的重复条目。

但是我如何告诉 hibernate 创建这些唯一的密钥?

因为

@Table
注释不接受本机sql语句。以下内容不够:

@Table(name = "person",
        uniqueConstraints = {@UniqueConstraint(name = "unique_person",
        columnNames = {"firstname", "lastname", "dob"}) }
)

问题:我怎样才能得到里面的

coalesce()

java spring hibernate jpa
1个回答
0
投票

基本上,如果值为空,您希望唯一约束不应该失败,一种简单的解决方案是将空白字符串(“”)作为默认值。 否则,您可以使用 @Formula 和 @NamedNativeQuery 进行实验,以指示 hibernate 如何处理它。

这是建议的块:

import javax.persistence.*;
import org.hibernate.annotations.SQLInsert;
import org.hibernate.annotations.Table;

@Entity
@Table(
    appliesTo = "person",
    uniqueConstraints = {
        @UniqueConstraint(
            name = "unique_person",
            columnNames = {
                "coalesced_firstname",
                "coalesced_lastname",
                "coalesced_dob"
            }
        )
    }
)
@NamedNativeQuery(
    name = "create_person_table",
    query = "CREATE TABLE person (id INT PRIMARY KEY, firstname VARCHAR(255), lastname VARCHAR(255), dob DATE, UNIQUE KEY unique_person ((coalesce(firstname, 'null')), (coalesce(lastname, 'null')), (coalesce(dob, 'null'))))"
)
@SQLInsert(sql = "INSERT INTO person (firstname, lastname, dob) VALUES (?, ?, ?)", callable = true)
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = true)
    private String firstname;

    @Column(nullable = true)
    private String lastname;

    @Column(nullable = true)
    private LocalDate dob;

    @Column(name = "coalesced_firstname", insertable = false, updatable = false)
    @org.hibernate.annotations.Formula("coalesce(firstname, 'null')")
    private String coalescedFirstname;

    @Column(name = "coalesced_lastname", insertable = false, updatable = false)
    @org.hibernate.annotations.Formula("coalesce(lastname, 'null')")
    private String coalescedLastname;

    @Column(name = "coalesced_dob", insertable = false, updatable = false)
    @org.hibernate.annotations.Formula("coalesce(dob, 'null')")
    private LocalDate coalescedDob;

    // Getters and setters
}

快乐编码!!有任何事情请随时联系。

© www.soinside.com 2019 - 2024. All rights reserved.