【问题标题】:Hibernate `unique` constraints not working if one of the multi-column constraint is null如果多列约束之一为空,则休眠“唯一”约束不起作用
【发布时间】:2018-02-06 14:40:59
【问题描述】:

Hibernate 中有一个名为unique 的约束,如果某个属性在验证时不是唯一的,则会引发错误。例如:

class Person {
    String id
    Person mother
    Person father
    String fullName

    // Mapping closure goes here

    static constraints = {
        father nullable: true
        fullName unique: ["mother", "father"]
        mother nullable: true
    }
}

在这种情况下,fullName 的任何值都是允许的,只要它在每个 motherfather 对上都是唯一的。因此,如果有一个Person 的记录,比如id=03 fullName=Liam,母亲id=01 fullName=Olivia 和父亲id=02 fullName=William,当另一个具有相同fullName id=04 fullName=Liam 的记录是在母亲id=01 fullName=Olivia 和父亲id=02 fullName=William 下插入。验证有效。

问题是当多列唯一约束之一是null。例如,当插入一条记录Personid=03 fullName=Liam,其母为id=01 fullName=Olivia 和一个nullfather,然后插入另一条具有相同fullNamemother 的记录,则不会触发验证。

我想知道这是否是一个限制。

附:我知道建议在数据库端有这个唯一的约束。我已经有了。我想要的是在 Hibernate 端进行等效检查。

【问题讨论】:

    标签: hibernate grails constraints


    【解决方案1】:

    我目前使用自定义验证器来捕获这个(这超出了使用 unique 约束的目的)。

    fullName unique: ["mother", "father"], validator { val, obj ->
        withSession { session ->
            Long count = Person.createCriteria().get {
                projections {
                    rowCount()
                }
    
                eq("mother", obj.mother)
                eq("father", obj.father)
                eq("fullName", obj.fullName)
                ne("id", obj.id)
            }
            if(count > 0) {
                return ["unique"]
            }
        }
    }
    

    并将这一行附加到message.property 文件中:

    person.fullName.unique=[{0}] with value {2} must be unique.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 2013-01-18
      • 1970-01-01
      相关资源
      最近更新 更多