I am using: Spring 4, Hibernate 4, SQL Server 2008
I know how to do it with SQL Server 2008 from this question response How do I create a unique constraint that also allows nulls?
But since I don't generate any manual SQL code during the creation of the table, is it possible to generate a "where clause" in my constraint through Hibernate annotations in my Entity class?
My DDL is created from scratch with the java entity definition as follows:
@Entity
@Table(name="Neighborhood",
uniqueConstraints = {@UniqueConstraint(columnNames = {"codecnbv","zipcode"})})
@JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY)
public class Neighborhood implements Serializable {
private String id;
private String codecnbv;
private String zipcode;
@Id
@Column(name="id", nullable=false, unique=true, length=2)
public String getId() {
return this.id;
}
@Column(name="codecnbv", nullable=true, length=12) //explicitly nullable
public String getCodecnbv() {
return codecnbv;
}
@Column(name="zipcode", nullable=true, length=5) //explicitly nullable
public String getZipcode() {
return zipcode;
}
}
However, as soon as I add data and try to enter a second record with NULL in column codecnbv and/or zipcode, I receive an exception that says I've violated the unique constraint.
The requirement I have says that I must allow multiple null values, and when the value is not null, then I should have unique values i.e.
For zipcode column
- 56000 --ok
- NULL --ok
- 34089 --ok
- NULL --ok
- 34089 --Not allowed
- 34567 --ok