在Grails中,如何基于其鉴别器在DB中搜索内容?
假设我有以下课程:在Grails中,如何基于其鉴别器在DB中搜索内容?,grails,discriminator,grails-2.0.4,Grails,Discriminator,Grails 2.0.4,假设我有以下课程: abstract class Fruit { String name static mapping = { discriminator column: 'type' } class Banana extends Fruit { static mapping = { discriminator: 'Banana' } } class Apple extends Fruit { static m
abstract class Fruit {
String name
static mapping = {
discriminator column: 'type'
}
class Banana extends Fruit {
static mapping = {
discriminator: 'Banana'
}
}
class Apple extends Fruit {
static mapping = {
discriminator: 'Apple'
}
}
我需要实现一个搜索算法,这样,给定一个JSON字符串,我就可以在DB中找到一个特定的Fruit实例。例如:
{
"type": "Apple"
"name": "Green"
}
或
问题是,水果可以有相同的名称,所以如果我只搜索一下:
Fruit.getByName('Green')
它可能返回苹果
或香蕉
。我需要能够根据类型对其进行过滤,例如:
Fruit.getByNameAndType('Green', 'Apple')
在Grails中如何实现这一点
Apple.getByName('Green')
应该有用。你试过了吗?看看生成的数据库 将有一个
class
列,您可以在水果类的条件搜索中使用该列
也许这是个好办法
Fruit.findAllByColorAndClassLike('Green','%Apple')
这是否也能满足您的需要
def fruits = Fruit.findAll("from Fruit where type = :type and name = :name", [type: "Apple", name: "Green"])
我认为你在回答问题之前没有仔细阅读这个问题。请再次阅读并更新您的答案。谢谢你,嗯。如果您能做一些类似于
defruit=“Apple”;“${fruit}.findByName(“绿色”)
Ralf:刚刚尝试过,显然您可以通过使用grailsApplication.getDomainClass('com.example.Apple').clazz.findByName('Green')让它工作
。请注意,类名必须完全限定才能工作。谢谢,我最终使用了with criteria
,它支持eq('class',name)
,其中name是鉴别器值。@DanielT.class
是否适用于您?因为您已将水果
类中的描述符列名重写为类型
def fruits = Fruit.findAll("from Fruit where type = :type and name = :name", [type: "Apple", name: "Green"])