Detach JPA objects with lazy initialized properties

蓝咒 提交于 2019-12-01 18:16:26

This method returns data well. But when I try access to received collection elements I catch exception: "org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: package.User.orders, no session or session was closed".

The error is self explaining: you are trying to load a (lazy) loaded collection but there is no active session anymore because the User instance is detached.

So, it was excepted. I thought that detaching result will solve my problem, but trick like this

This won't change anything. The EntityManager#detach(Object) method doesn't load anything, it removes the passed entity from the persistence context, making it detached.

It doesn't matter for me will info about users attend in set of orders or not. I just want to work with this set and not going to modify it.

You need to either make the association EAGER (so that Orders will be loaded when retrieving a User) or to use a FETCH JOIN when retrieving a user in your service:

SELECT u
FROM User u LEFT JOIN FETCH u.orders
WHERE u.id = :id

Do I understand correctly that hibernate has no standard mechanism for force load all lazy associations of current object

Hibernate has a Hibernate.initialize method, but this is obviously not standard JPA (prefer fetch join for portable code).

I have no way to make hibernate ignore lazy associations of current object (set them as null)

What? What do you mean by ignore? Why would you do that anyway?

The LazyInitialisationException occurs because data is requested outside a transaction. If you need that data, you must request it within a transaction - in your case, this would be within the service method.

You can request the data to be loaded in several ways. The easiest:

for(Order order: orders)
    order.getX()

(where X is some property other than Id or version)

This however will load each order in a seperate query, which is slow if there are many orders. A faster approach would be to issue a query (JP-QL or Criteria) returning all orders of that user. (Edit: See Pascal's answer for a suitable query.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!