我有一个包含两个字段的实体:
@ManyToOne(fetch = FetchType.LAZY, optional = true)
private Organization organization;
@Column(length = 15)
private String ref;我想在organization和ref上添加唯一键,只有当organization和ref都不是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'这两种情况都会产生约束冲突,我不想这样做,因为我只希望唯一的约束在只有organization和ref都不是null的情况下才有效。
我就是这样声明唯一约束的:
@Table(uniqueConstraints = {
@UniqueConstraint(columnNames = { "organization", "ref" })
})我该怎么解决这个问题。
PS:我正在使用Oracle 12c。
编辑:
organization和ref这两个字段都是空的。联合行动纲领发布于 2017-12-14 11:01:20
您需要为此创建一个基于函数的索引。
CREATE UNIQUE INDEX uidx_my_table ON my_table
(CASE WHEN organization IS NOT NULL AND ref IS NOT NULL
THEN organization || ref
END);发布于 2017-12-14 11:52:49
甲骨文对于惟一的索引相当奇怪:
升序唯一索引允许多个空值。但是,在降序唯一索引中,多个空值被视为重复值,因此不允许。
因此,您可以通过一个唯一的索引来处理这个问题:
create unique index unq_t_organization_ref on t(organization, ref);索引应忽略唯一值。
https://stackoverflow.com/questions/47811273
复制相似问题