Grails:按名称查找域类

时间:2011-06-14 01:25:05

标签: grails grails-domain-class servlets

我想允许用户遍历域类并打印出垃圾堆。我的第一个问题:假设以下工作正常:

//this works
class EasyStuffController{
  def quickStuff = {
    def findAThing = MyDomainClass.findByStuff(params.stuff)
    [foundThing:findAThing]
  }
}

写下我想说的内容的正确方法是什么:

//this doesn't
class EasyStuffController{ servletContext ->
  def quickStuff = {
    def classNameString = "MyDomainClass" //or params.whichOne something like that
    def domainHandle = grailsApplication.domainClasses.findByFullName(classNameString)
    //no such property findByFullName
    def findAThing = domainHandle.findByStuff(params.stuff)
    [foundThing:findAThing]
  }
}



//this also doesn't
class EasyStuffController{ servletContext ->
  def quickStuff = {
    def classNameString = "MyDomainClass" //or params.whichOne something like that
    def domainHandle 
    grailsApplication.domainClasses.each{
      if(it.fullName==classNameString)domainHandle=it
    }
    def findAThing = domainHandle.findByStuff(params.stuff)
    //No signature of method: org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass.list() is applicable
    [foundThing:findAThing]
  }
}

上面的那些行根本不起作用。我试图让用户能够选择任何域类,并用“东西”取回东西。假设:所有域类都有一个相同类型的Stuff字段。

1 个答案:

答案 0 :(得分:44)

如果您知道整个包裹,可以使用:

String className = "com.foo.bar.MyDomainClass"
Class clazz = grailsApplication.getDomainClass(className).clazz
def findAThing = clazz.findByStuff(params.stuff)

如果你不使用包,这也会有效。

如果您使用套餐但用户只提供没有套餐的类名,并且名称在所有套餐中都是唯一的,那么您可以使用:

String className = "MyDomainClass"
Class clazz = grailsApplication.domainClasses.find { it.clazz.simpleName == className }.clazz
def findAThing = clazz.findByStuff(params.stuff)