【问题标题】:Grails domain validation does not workGrails 域验证不起作用
【发布时间】:2016-06-01 16:04:01
【问题描述】:

我正在使用 Grails 2.5.4,似乎基于域对象中定义的约束的验证不起作用。给定:

class Pet {

    String name

    static constraints = {
        name(nullable: false, blank: false)
    }
}

当我使用如下代码进行测试时:

    Pet p = new Pet()
    if(!p.save()) {
        p.errors.each {
            println it
        }
    }

我希望在控制台上看到验证输出。相反,我在 save() 上收到运行时异常:

Class
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException
Message
Column 'name' cannot be null

这不是我所期望的行为。当验证未通过时,save() 不应该进行 MySQL 插入调用。有谁知道问题是什么?

我还测试了以下内容:

    Pet e = new Pet()
    e.validate()
    println e.hasErrors()  

我得到了错误的输出,这是不正确的。

当我给宠物起名字时,插入效果很好。所以设置似乎没问题。只是验证似乎不起作用。

【问题讨论】:

  • 如果您可以提供一个示例应用程序来演示该行为,那么找出问题所在将是微不足道的。
  • 默认情况下,属性不为空,空字符串通过数据绑定转换为空,所以约束name(nullable: false, blank: false)在很大程度上是多余的

标签: hibernate validation grails grails-orm


【解决方案1】:

这对我来说没有意义。我会在 constraints 这个词中查找错字。

https://github.com/jeffbrown/validationstuff 的项目包含以下域类:

// grails-app/domain/demp/Pet.groovy
package demo

class Pet {
    String name

    static constraints = {
        name(nullable: false, blank: false)
    }
}

以下控制器:

// grails-app/controllers/demo/DemoController.groovy
package demo

class DemoController {

    def index() {
        def p = new Pet()
        p.validate()
        def hasErrors = p.hasErrors()

        render "Has Errors? $hasErrors"
    }
}

还有以下测试:

// test/unit/demo/DemoControllerSpec.groovy
package demo

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(DemoController)
@Mock(Pet)
class DemoControllerSpec extends Specification {

    void "test validation"() {
        when:
        controller.index()

        then:
        response.text == 'Has Errors? true'
    }
}

// test/unit/demo/PetSpec.groovy
package demo

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(Pet)
class PetSpec extends Specification {

    void "test constraints"() {
        expect:
        !new Pet().validate()
    }
}

该应用包含以下 BootStrap:

// grails-app/conf/BootStrap.groovy
class BootStrap {

    def init = { servletContext ->
        def pet = new demo.Pet()
        pet.validate()

        println "Has Errors? ${pet.hasErrors()}"
    }
    def destroy = {
    }
}

在应用程序启动时:

Has Errors? true

【讨论】:

    【解决方案2】:

    问题出在 5.0.4 版本的休眠插件依赖

    似乎该版本无法识别 grails 2.x 域类。

    我升级到 5.0.8 并解决了问题。

    【讨论】:

      猜你喜欢
      • 2015-06-07
      • 1970-01-01
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      相关资源
      最近更新 更多