Query criteria in subclass on Grails 3

66 Views Asked by At

I have a domain like this:

class Container {
  Content content
}

class Content {
}

class ContentAlpha extends Content {
  String name
}

class ContentBeta extends Content {
  int length
}

Then I have a criteria:

def result = Container.withCriteria {
  content {
    eq('name', 'Pablo')
  }
}

How can I get all the containers that contain just ContentAlpha that match the value given for the 'name'?

1

There are 1 best solutions below

3
rchfox On

I think the withCriteria closure you are trying to use is conceptually wrong, from the OOP perspective.

Generally speaking, a superclass does not contain information about its subclasses. In contrast, a subclass does contain information about its superclass.

In your example, an instance of ContentAlpha is a Content also. But, an instance of Content is not a ContentAlpha. Therefore, you cannot query content.name, because name does not exists as a property of Content class.

Having said that, let me suggest a rudimentary tip (acknowledging that I don't know the context of the problem you are trying to solve, and assuming you can't change your domains' relations):

You could add a couple of static functions in Container.groovy:

static def queryContent(String name) {
   return Container.findAllByContentInList(ContentAlpha.findAllByName(name))
}
    
static def queryContent(int length) {
   return Container.findAllByContentInList(ContentBeta.findAllByLength(length))
}

Then you could do something like this:

def containersA = Container.queryContent("Pablo")
def containersB = Container.queryContent(4000)