java - 如何创建一个允许 NULL 值与 Hibernate 注释的唯一约束?

标签 java sql-server hibernate

我正在使用: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 的第二条记录,我就会收到一个异常,提示我违反了唯一约束。

我的要求是我必须允许多个空值,当值不为空时,我应该有唯一值,即

对于邮政编码列

  1. 56000 --好的
  2. NULL --ok
  3. 34089 --好的
  4. NULL --ok
  5. 34089 --不允许
  6. 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/

相关文章:

hibernate - Hibernate 查询语言中的 LEFT JOIN

java - 在哪里检查包是否随 JRE for Java 一起提供

java - 查看 SBT 发出的确切 java 命令

sql - 在 Windows Server 2003 企业版上并排安装 SQL Server 2008 R2 和 MySQL 是否安全?

sql-server - SQL : Distinct Medications to Columns Using Pivot

performance - 使用 Spring 3.1、Hibernate 4.1、Dbunit 等提高数据库测试的性能

java - Hibernate 映射 - 通过表进行映射

java - 不同的ip连接mysql

java - Spring容器是否调用bean的构造函数?如果不是,如何使用 "new"关键字将字段初始化为新实例?

sql-server - 为什么 AsNoTracking 会影响 DateTime 精度?