简体   繁体   中英

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.

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.

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.

Edit :

  • Both fields organization and ref are nullable. The JPA

  • @UniqueConstraint annotation I declared will generate the SQL code:

    CREATE UNIQUE INDEX "USERNAME"."UK_TABLENAME_1" ON "USERNAME"."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:

Ascending unique indexes allow multiple NULL values. However, in descending unique indexes, multiple NULL values are treated as duplicate values and therefore are not permitted.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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