0

从演示如何在 Grails 之外使用 GORM 的github 存储库开始,我尝试使用动态查找器,以便可以通过其属性之一查找特定域对象。在这个例子中,我们在 groovy 中有这个 person 对象,如下所示:

package domain

import grails.gorm.annotation.Entity
import org.grails.datastore.gorm.GormEntity

@Entity
class Person implements GormEntity<Person> {

    String firstName
    String lastName

    static mapping = {
        firstName blank: false
        lastName blank: false
    }
}

现在假设我想按姓氏查找一个人。我应该能够使用 GORM 增强的 Person 实体方法findByLastName。我能够编译尝试这样做的代码,但是当我在运行时调用它时,找不到该方法。

我向 PersonSpec.groovy 添加了一个测试方法,如下所示:

   @Rollback
   def "person can be found by last name"() {
      when:
      def p = new Person(firstName: 'Scott', lastName: 'Ericsson')
      p.save(flush: true)

      def foundPerson = p.findByLastName('Ericsson')

      then:
      foundPerson.firstName == 'Scott'
   }

运行测试时出现此错误:

domain.PersonSpec > person can be found by last name FAILED
    groovy.lang.MissingMethodException at PersonSpec.groovy:32

它上面的测试方法成功地创建并保存了一个人记录,因此 GORM 功能的某些方面正在工作。但是动态查找器功能在运行时没有被正确应用,即使编译器认为一切看起来都很好。

我的整个 build.gradle 是这样的:

apply plugin: 'groovy'

repositories {
    jcenter()
}

dependencies {
   compile "org.hibernate:hibernate-validator:5.3.4.Final"
   compile "org.grails:grails-datastore-gorm-hibernate5:7.0.0.RELEASE"
   runtime "com.h2database:h2:1.4.192"
   runtime "org.apache.tomcat:tomcat-jdbc:8.5.0"
   runtime "org.apache.tomcat.embed:tomcat-embed-logging-log4j:8.5.0"
   runtime "org.slf4j:slf4j-api:1.7.10"

   testCompile 'org.spockframework:spock-core:1.1-groovy-2.4'
}

有谁知道我错过了什么?

4

1 回答 1

2

所以我已经为此苦苦挣扎了几天,你不知道我一发布问题就知道了,我几乎立刻就明白了。这很简单——我需要在 Person 对象而不是 person 实例上静态使用 findByLastName 方法。现在在 PersonSpec 中工作的代码如下所示:

   @Rollback
   def "person can be found by last name"() {
      when:
      def p = new Person(firstName: 'Scott', lastName: 'Ericsson')
      p.save(flush: true)

      def foundPerson = Person.findByLastName('Ericsson')

      then:
      foundPerson.firstName == 'Scott'
   }
于 2019-04-16T19:12:55.173 回答