我正在使用:Spring 4、Hibernate 4、SQL Server 2008
我从这个问题响应 How do I create a unique constraint that also allows nulls? 知道如何使用 SQL Server 2008
但是由于我在创建表的过程中没有生成任何手动 SQL 代码,是否可以通过我的实体类中的 Hibernate 注释在我的约束中生成一个“where 子句”?
我的 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;
}
但是,一旦我添加数据并尝试在 codecnbv 和/或 zipcode 列中输入带有 NULL 的第二条记录,我就会收到一个异常,提示我违反了唯一约束。
我的要求是我必须允许多个空值,当值不为空时,我应该有唯一值,即
对于邮政编码列
- 56000 --好的
- NULL --ok
- 34089 --好的
- NULL --ok
- 34089 --不允许
- 34567 --好的
最佳答案
这不是 Hibernate 的问题,而是 SQL Server 的问题,SQL Server 将 NULL
视为一个值并且不允许第二个 NULL
值。邪恶的,我知道。
一些链接:
How do I create a unique constraint that also allows nulls?
http://sqlmag.com/database-development/multiple-nulls-unique-constraints
关于java - 如何创建一个允许 NULL 值与 Hibernate 注释的唯一约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22155244/