Hibernate won't initialize proxy

2019-09-07 01:02发布

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?

2条回答
迷人小祖宗
2楼-- · 2019-09-07 01:25

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.

查看更多
姐就是有狂的资本
3楼-- · 2019-09-07 01:34

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)

查看更多
登录 后发表回答