Grails / Groovy domain class inheritance

I modeled my domain classes in Grails with inheritance as shown below.

abstract class Profile{ } class Team extends Profile{ } class User extends Profile{ } class B{ static hasMany = [profiles: Profile] } 

Later in controllers, when I get all profiles from class B in some situations, I would like to drop some profiles in Team or in User, but I cannot, because I get java.lang.ClassCastException or GroovyCastException, although they are saved as a command or user (with an attribute class in the database). Here is how I tried:

 def team1 = b.profiles.toList()[0] as Team def team1 = (Team)b.profiles.toList()[0] 

It works when I do not write any type, just use it, as is normal in a dynamic language.

 def team1 = b.profiles.toList()[0] 

But then I never know which class I use. Is there a groovy or gorm to pass a parent class to a child?

+6
source share
1 answer

Answer No , because the actual instance of GORM / Hibernate is a proxy object. Therefore, it cannot be directly passed to the entity class.

In any case, this may help:

 def team1 = b.profiles.toList()[0] if(team1.instanceOf(Team)) { // I am an instance of Team // do something here. } 
+4
source

Source: https://habr.com/ru/post/920201/


All Articles