简体   繁体   中英

How to get the actual instance of a domain class in grails?

I have two classes ClassA and ClassB

class ClassA{
    String userName
    String passwd

    .....
}

class ClassB extends ClassA{
    String address_line1
    String address_line2

    .....
}

If I am quering

ClassA obj = ClassA.get(1)

I am getting the instance of ClassB. How do I get the actual instance of ClassA.

Thanks

Nimmy..

You have to use code like this:

def obj = ClassA.get( 1 )

You hit one of the GORM gotchas, there is a must-reading article by SpringSource blog: http://blog.springsource.org/2010/07/28/gorm-gotchas-part-3/ (Chapter Proxies). I recommend to read all 3 articles! You'll understand, what is going under the hood much better :-)

Additional information. by default, Grails are using "hierarchy per table" strategy, when mapping class hierarchy, so if you're creating ClassB, it is saved in the same table like ClassA, so they are sharing the same Primary Key column. That's why you get ClassB instead of ClassA. GORM returns the correct class instance based on a type column, which contains the infromation, which class of the hierarchy is stored at the row you want. But you can retype explicitly, if you want ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM