【问题标题】:Grails: querying hasMany associationGrails:查询 hasMany 关联
【发布时间】:2012-05-01 17:07:16
【问题描述】:

我知道关于这个主题有几个问题,但似乎没有一个对我有用。我有一个带有以下域对象的 Grails 应用程序:

class Tag {
    String name
}

class SystemTag extends Tag {
    // Will have additional properties here...just placeholder for now
}

class Location {
    String name
    Set<Tag> tags = []
    static hasMany = [tags: Tag]
}

我正在尝试查询已被 1 个或多个标签标记的所有 Location 对象:

class LocationQueryTests {

    @Test
    public void testTagsQuery() {
        def tag = new SystemTag(name: "My Locations").save(failOnError: true)
        def locationNames = ["L1","L2","L3","L4","L5"]
        def locations = []
        locationNames.each {
            locations << new Location(name: it).save(failOnError: true)
        }
        (2..4).each {
            locations[it].tags << tag
            locations[it].save(failOnError: true)
        }

        def results = Location.withCriteria {
            tags {
                'in'('name', [tag.name])
            }
        }

        assertEquals(3, results.size())     // Returning 0 results
    }
}

我已验证数据正在正确创建/设置...已创建 5 个位置对象,其中最后 3 个已标记。

我看不出上述查询有什么问题。我真的很想远离 HQL,我相信这应该是可能的。

【问题讨论】:

  • Location.count() 返回 5?您可能需要将 flush: true 添加到您的保存调用中。

标签: grails grails-orm


【解决方案1】:

欢迎来到休眠。

save 方法通知持久性上下文应该保存或更新一个实例。除非使用 flush 参数,否则对象不会立即持久化

如果您不使用刷新,它会批量保存,因此当您在保存后立即设置查询时,似乎数据不存在。

你需要添加

 locations[it].save(failOnError: true, flush:true)

【讨论】:

  • 废话……就是这样。感谢您的回答!
【解决方案2】:

您应该使用addTo* 为一对多或多对多关系添加域类关系。

(2..4).each {
    locations[it].addToTags(tag)
}

【讨论】:

  • 感谢您的指点...我似乎总是忘记 addTo* 方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-09
  • 2011-01-04
相关资源
最近更新 更多