views:

320

answers:

1

I need to serialize the result of a jpql query (meaning I need to serialize all the jpa beans). I want to get all nested relationship (even if they are lazy loaded) so that the client can deserialize on the other end without getting error. Is there a way to do that?

A: 

I think your options are either:

  1. Use Eager loading before serialization.
  2. Have the client merge the de-serialized bean into an EntityManager and then read the lazy-loaders as necessary.
Steve Claridge
For #1, Can you force eager loading on doing the query: List results = em.createQuery(query).getResultList(); ?How can I force all the beans in the result to be eager load even if the beans didn't specify those relationship as (fetch=FetchType.EAGER)?
You could change the annotations to be eager using reflection before you do the query for the times when you want to serialize - leave lazy the rest of the time. Or Alternatively: after doing the query read each collectiom of lazy-loaded reference to force the read. I don't think it is possible to force eager load from the query, you have to modify the entity. Seems odd that you want to serialize but use lazy loading - do you have times when you want it lazy and times when eager? Maybe reflection would work for you?
Steve Claridge
The problem with declaring all the relationship eager load is that you can somethings run into problem of exceed the maxium size of the rowsize because eager loading will generate one single complex join. So if you have many beans and a lot of nested relationship, you can actually reach a maxium rowsize limit error. That is why the relationship are by default lazy in many cases.