gpt4 book ai didi

java - 对两个非空字段添加唯一约束

转载 作者:太空宇宙 更新时间:2023-11-04 10:51:21 25 4
gpt4 key购买 nike

我有一个包含两个字段的实体:

@ManyToOne(fetch = FetchType.LAZY, optional = true)
private Organization organization;

@Column(length = 15)
private String ref;

我想在 organizationref 上添加唯一键,此唯一键仅在 organizationref 都不为 null 时才有效。

例如,当我插入两条记录时:

organization = 1, ref = 'R1'

organization = 1, ref = 'R1'

这将产生约束违规,到目前为止我对这种情况没有任何问题。

当我插入两条记录时:

organization = null, ref = null

organization = null, ref = null

这不会产生约束违规,到目前为止我对这种情况也没有任何问题。

我遇到的问题是在这种情况下:

organization = 1, ref = null

organization = 1, ref = null

或者

organization = null, ref = 'R1'

organization = null, ref = 'R1'

这两种情况都会产生约束违规,这是我不希望的,因为我只希望只有 organizationref 都不为 null 时唯一约束才有效。

这就是我声明唯一约束的方式:

@Table(uniqueConstraints = {
@UniqueConstraint(columnNames = { "organization", "ref" })
})

我该如何解决这个问题。

PS:我使用的是 Oracle 12c。

编辑:

  • organizationref 字段都可为空。 JPA

  • 我声明的@UniqueConstraint注释将生成SQL代码:

    在“USERNAME”.“TABLENAME”(“organization”、“ref”)上创建唯一索引“USERNAME”.“UK_TABLENAME_1”

最佳答案

您需要为此创建一个基于函数的索引。

CREATE UNIQUE INDEX uidx_my_table ON my_table
(CASE WHEN organization IS NOT NULL AND ref IS NOT NULL
THEN organization || ref
END);

关于java - 对两个非空字段添加唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47811273/

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