Search code examples
grailsinheritancegrails-orm

Creating a Super Object from its base type (Grails)


I have 2 domain classes. One of them is User and the other is SuperUser. The super user contains some extra fields, and SuperUser inherits from User. (Also to note: User has the mapping to set inheritTableHeirachy set to false).

How can I cast the existing User instance object to a SuperUser? Is there a way that I can pass it in the SuperUser constructor?

I want to keep the reference to the original user, and I want to add the extra properties of SuperUser to the SuperUser table.


Solution

  • There is the way via properties. You maybe want to eradicate the ID afterwards or filter already before, what you don't need (it's a map). E.g.

    new SuperUser(theUser.properties)
    

    Since this only "copies" the same property names, there is no protection against setting "stupid" things. Both objects don't have to be of the same class hierarchy etc. It is just calling the c'tor for maps with a map.

    A more structured way would be the introduction of an adaptor for this case.