title: How can I create a Unique Constraint that allows NULL values with Hibernate annotations?
body: <p>I am using: Spring 4, Hibernate 4, SQL Server 2008</p>
  
  <p>I know how to do it with SQL Server 2008 from this question response <a href="https://stackoverflow.com/questions/767657/how-do-i-create-a-unique-constraint-that-also-allows-nulls">How do I create a unique constraint that also allows nulls?</a> </p>
  
  <p>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? </p>
  
  <p>My DDL is created from scratch with the java entity definition as follows:</p>
  
  <pre><code>@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;
  }
  </code></pre>
  
  <p>}</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>For zipcode column</p>
  
  <ol>
  <li>56000  --ok</li>
  <li>NULL   --ok</li>
  <li>34089  --ok</li>
  <li>NULL   --ok</li>
  <li>34089  --Not allowed</li>
  <li>34567  --ok</li>
  </ol>