【问题标题】:GORM for Hibernate outside of Grails在 Grails 之外用于 Hibernate 的 GORM
【发布时间】:2019-04-16 19:02:16
【问题描述】:

从演示如何在 Grails 之外使用 GORM 的 github repo 开始,我尝试使用动态查找器,以便可以通过其属性之一查找特定域对象。在这个例子中,我们在 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'
}

有人知道我错过了什么吗?

【问题讨论】:

  • 添加 `testCompile 'org.grails:grails-datastore-gorm-test:7.0.0.RELEASE' 有改善吗?至少对于 grails,需要一些专用的测试库。

标签: grails dynamic-finders


【解决方案1】:

所以我已经为此苦苦挣扎了几天,您不知道我发布问题后我几乎立即就知道了。这很简单——我需要在 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'
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 2011-10-04
    • 2011-09-17
    • 1970-01-01
    • 2011-09-20
    相关资源
    最近更新 更多