0

I've got this mappings in Hibernate (through JPA, using EntityManager and such):

 public ChildClass {

     ....
      @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "parentClassId")
        private ParentClass parentClass;
     ....
    }

And a parent class that has a list of ChildClass elements:

 public ParentClass {
    ...
    @OneToMany(mappedBy = "parentClass", fetch = FetchType.LAZY)
        private List<ChildClass> childElements;
    ...

    }   

Now I have this method in my Service layer:

@Transactional
public ChildClassDTO consultarPuntuacionPrueba(Long parentClassId) {
            ChildClass result= childClassDAO.getChildClassByParentId(parentClassId);



            ParentClass parentClass = result.getParentClass();

            System.out.println("UNITIALIZED: " + ((HibernateProxy)prueba).getHibernateLazyInitializer().isUninitialized());


            Long parentClassId = parentClass.getParentClassId();
            Boolean anAttribute = parentClass.getBooleanAttribute();

            return map(result, ChildClassDTO.class);
        }

The problem is -- parentClass is a javassist proxy, and even though when accessing a getter of parentClass, I can see a query getting executed (it shows in my console), the proxy never gets initialized and holds null for all attributes... I have tried said query directly towards my database, and it returns the expected data.

I know Hibernate must return a proxy when I call childClass.getParentClass(), but why is it never initialized afterwards?

HavelTheGreat
  • 3,159
  • 1
  • 12
  • 32
Gabriel Sanmartin
  • 3,504
  • 13
  • 47
  • 100

2 Answers2

2

Make sure your don't use the final keyword for your entities getters and setters otherwise the proxies will not be able to override the methods and may not work properly.

David Levesque
  • 20,680
  • 8
  • 62
  • 78
0

As you defined in the mapping, Hibernate loads the mapped entity lazily. That means the mapped entity is only loaded when you access it (otherwise you only have a proxy instance). So you could change the FetchType to EAGER if you would like that the mapped entity is eagerly loaded (without a proxy)

Lorenz Pfisterer
  • 762
  • 5
  • 16
  • That's not my question -- as I stated in my OP, I know it's lazily loaded and Im okay with that, the problem is *after* accessing the proxies' properties, I still get null values cause the proxy won't get initialized even after the proper query has been made – Gabriel Sanmartin Feb 11 '15 at 16:52
  • That is indeed very strange – Lorenz Pfisterer Feb 11 '15 at 16:59