Search code examples
grailsgrails-orm

get inherited class using id and not knowing the class type


I have a couple inherited classes from a base class. My gsp lists the subclasses, so I know what the type of each class in the list.

tablePerHierarchy is false, so I have one table that holds all inherited classes.

abstract class Base {
}

public class Sub1 extends Base {
}

public class Sub2 extends Base {
}

list.gsp:

<g:link action="show" id="${item.id}"/>

in my controller how can I get the correct Sub1/Sub2 instance if only the row id is known?

For example, here is what I don't want to do (2 queries):

Base.get(id)

figure out the class from the base, say its Sub2

get the real object:

Sub2.get(id)

Is there something like:

Here is the id, get me the fully derived class based on the id with one query.


Solution

  • I'm not sure if I understand your question correctly. When you do Base.get(id), GORM (with Hibernate) returns the real instance automatically which in this case is either of Sub1 or Sub2. You don't have to call Sub1.get(id) again.

    If you want to check if the returned instance is of Sub1 or Sub2, you can do:

    def instance = Base.get(id)
    if (instance.instanceOf(Sub1))
      instance.doSub1Operation()
    else if (instance.instanceOf(Sub2))
      instance.doSub2Operation
    else
      throw new RuntimeException("Unknown instance type")