How can I create a Unique Constraint that allows NULL values with Hibernate annotations?


  •  19-10-2022
  •  | 


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:

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;

@Column(name="id", nullable=false, unique=true, length=2)
public String getId() {

@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

  1. 56000 --ok
  2. NULL --ok
  3. 34089 --ok
  4. NULL --ok
  5. 34089 --Not allowed
  6. 34567 --ok



It is not an issue of Hibernate but of SQL Server, which considers NULL a value and does not allow a second NULL value. Wicked, I know.

Some links:

How do I create a unique constraint that also allows nulls?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top