简体   繁体   English

在两个非空字段上添加唯一约束

[英]Add unique constraint on two not null fields

I have an entity that contains the two fields: 我有一个包含两个字段的实体:

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

@Column(length = 15)
private String ref;

I want to add unique key on organization and ref this unique key will only be valid if the organization and ref are both not null. 我想在organization上添加唯一键并ref该唯一键仅在organizationref都不为空时才有效。

For example when I insert two record where: 例如,当我插入两条记录时:

organization = 1, ref = 'R1'

organization = 1, ref = 'R1'

This will generate a constraint violation, so far I have no problem with this case. 这将产生约束冲突,到目前为止,我对这种情况没有任何疑问。

And when I insert two record where: 当我插入两条记录时:

organization = null, ref = null

organization = null, ref = null

This won't generate a constraint violation, so far I have no problem with this case either. 这不会产生约束违规,到目前为止,我对这种情况也没有问题。

The problem I have is in this case : 我遇到的问题是在这种情况下:

organization = 1, ref = null

organization = 1, ref = null

Or 要么

organization = null, ref = 'R1'

organization = null, ref = 'R1'

This both cases are generating a constraint violation, which I don't want, since I only want the unique constraint to be valid if only organization and ref are both not null. 这两种情况都产生了约束冲突,这是我不希望的,因为我只希望唯一的约束在只有organizationref都不为空的情况下才有效。

This is how I declared the unique constraint : 这就是我声明唯一约束的方式:

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

How can I solve this. 我该如何解决。

PS: I'm using Oracle 12c. PS:我正在使用Oracle 12c。

Edit : 编辑:

  • Both fields organization and ref are nullable. 字段organizationref都可以为空。 The JPA JPA

  • @UniqueConstraint annotation I declared will generate the SQL code: 我声明的@UniqueConstraint批注将生成SQL代码:

    CREATE UNIQUE INDEX "USERNAME"."UK_TABLENAME_1" ON "USERNAME"."TABLENAME" ("organization", "ref") 在“ USERNAME”上创建唯一索引“ USERNAME”。“ UK_TABLENAME_1”。“ TABLENAME”(“ organization”,“ ref”)

You need to create a function based index for this. 您需要为此创建一个基于函数的索引。

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

Oracle is rather strange about unique indexes: Oracle对于唯一索引颇为奇怪:

Ascending unique indexes allow multiple NULL values. 唯一索引升序允许多个NULL值。 However, in descending unique indexes, multiple NULL values are treated as duplicate values and therefore are not permitted. 但是,在降序唯一索引中,多个NULL值被视为重复值,因此是不允许的。

So, you can handle this with a unique index: 因此,您可以使用唯一索引来处理此问题:

create unique index unq_t_organization_ref on t(organization, ref);

The unique values should be ignored by the index. 索引应忽略唯一值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM