简体   繁体   English

如何使用 Hibernate 注释创建允许 NULL 值的唯一约束?

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

I am using: Spring 4, Hibernate 4, SQL Server 2008我正在使用: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?我知道如何从这个问题响应中使用 SQL Server 2008 如何创建一个也允许空值的唯一约束?

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?但是由于我在创建表的过程中没有生成任何手动 SQL 代码,是否可以通过我的实体类中的 Hibernate 注释在我的约束中生成一个“where 子句”?

My DDL is created from scratch with the java entity definition as follows:我的 DDL 是使用 java 实体定义从头开始创建的,如下所示:

@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.但是,一旦我添加数据并尝试在列 codecnbv 和/或邮政编码中输入带有 NULL 的第二条记录,我就会收到一个异常,表明我违反了唯一约束。

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 ie我的要求说我必须允许多个空值,当值不为空时,我应该有唯一的值,即

For zipcode column对于邮政编码列

  1. 56000 --ok 56000 --好的
  2. NULL --ok空 --ok
  3. 34089 --ok 34089 --好的
  4. NULL --ok空 --ok
  5. 34089 --Not allowed 34089 --不允许
  6. 34567 --ok 34567——好的

It is not an issue of Hibernate but of SQL Server, which considers NULL a value and does not allow a second NULL value.这不是 Hibernate 的问题,而是 SQL Server 的问题,它认为NULL是一个值并且不允许第二个NULL值。 Wicked, I know.邪恶,我知道。

Some links:一些链接:

How do I create a unique constraint that also allows nulls? 如何创建一个也允许空值的唯一约束?

http://sqlmag.com/database-development/multiple-nulls-unique-constraints http://sqlmag.com/database-development/multiple-nulls-unique-constraints

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

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