Search code examples
hibernategrailsgroovyproxygrails-orm

Removing proxy part of grails domain object?


I want to get at an actual instance of a domain object. That is, I need to serialize the object, and I'm trying to use the domain object on two sides of an httpinvoker chain. Is there a way to get a fully-loaded domain object that doesn't have any grails wiring, so that I can serialize it?


Solution

  • We do GrailsHibernateUtil.unwrapIfProxy(obj). It won't get rid of Grails injected methods and such - only of Hibernate/GORM proxy, but it should be sufficient.

    edit:

    1. Sorry for asking, but did you declare your domain class as implements Serializable?
    2. It might be something you add/inject into your class, like in Grails non-bug 6379.
    3. This piece of code (got it here) worked for me in grails console on a small domain class:

    .

    import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil
    import com.somegroup.domain.*
    
    def loc = SomeDomainClass.get(1)
    loc = GrailsHibernateUtil.unwrapIfProxy(loc)
    
    ByteArrayOutputStream bos = new ByteArrayOutputStream()
    ObjectOutput out = new ObjectOutputStream(bos)
    
    out.writeObject(loc)
    byte[] yourBytes = bos.toByteArray()