2 Replies Latest reply on Jun 1, 2010 8:42 AM by trashbat

    ManyToOne & lazy initialization

    trashbat

      Hi,

       

      I'm fairly sure this is a simple task, but I can't find much about it, so please bear with me.

       

      I've got an audited entity called Category. When something happens to one of them, on update or persist, I want to create change reports. Therefore I pull the last copy up using AuditReader and compare its properties. For the simple properties, this works fine.

       

      However Category also has a 'parent' property, another Category. getParentCategory() is annotated with @ManyToOne.

       

      When I try to pull this from my Category object, I get a lazy initialization handler, and thus getParentCategory().getWhatever() returns null. I see it has the parent's correct ID in the handler's details, which would be enough for my purposes, but I can't get at that.

       

      I don't want to merge the old object back in, only examine it. I've tried annotating getParentCategory() with:

       

      @ManyToOne(optional = true, fetch=FetchType.EAGER)

       

      but it has no effect.

       

      What can I do?

       

      Cheers,

       

      Rob

        • 1. Re: ManyToOne & lazy initialization
          adamw

          Just to make sure, you've got an audited relation, and you call entity.getRelatedEntity().getSomeProperty() and you don't get the expected result?

          What is null in your case?

           

          Adam

          • 2. Re: ManyToOne & lazy initialization
            trashbat

            Sorry, been away on holiday.

             

            Yes, exactly that. The property is null because getRelatedEntity() returns a proxy.

             

            However I have resolved my problem by calling Hibernate.initialize() on the entity and property. Reading around, this is probably fairly obvious, but I didn't expect it to be lazy in the first place.