Search code examples
hibernatelazy-loadingtostring

How do I implement toString() in a class that is mapped with Hibernate?


I have an instance of a class that I got from a Hibernate session. That session is long gone. Now, I'm calling toString() and I'm getting the expected LazyInitializationException: could not initialize proxy - no Session since I'm trying to access a reference which Hibernate didn't resolve during loading of the instance (lazy loading).

I don't really want to make the loading eager since it would change the query from about 120 characters to over 4KB (with eight joins). And I don't have to: All I want to display in toString() is the ID of the referenced object; i.e. something that Hibernate needs to know at this point in time (or it couldn't do the lazy loading).

So my question: How do you handle this case? Never try to use references in toString()? Or do you call toString() in the loading code just in case? Or is there some utility function in Hibernate which will return something useful when I pass it a reference which might be lazy? Or do you avoid references in toString() altogether?


Solution

  • It's possible to do this by setting the accesstype of the ID field to "property". like:

    @Entity
    public class Foo {
        // the id field is set to be property accessed
        @Id @GeneratedValue @AccessType("property")
        private long id;
        // other fields can use the field access type
        @Column private String stuff;
        public long getId() { return id; }
        public void setId(long id) { this.id = id; }
        String getStuff() { return stuff; }
        // NOTE: we don't need a setStuff method
    }
    

    It's explained here. This way the id field is allways populated when a proxy is created.