reattach entity in request scope entitymanager
I have an web application where the user makes a selection and right below using ajax, the details of the selection needs to show up. For example, User selects a Person on the top fra开发者_C百科me and in the bottom frame all person details show up. there are a bunch of collection in person that are lazily loaded. When any of the collection are called, I get a lazyinitialization exception, which is expected. how do I avoid this. how do i reattach entites to the entityManager after an ajax call.
There are a few ways of doing what you are doing here :
- Use eager loading for all the collections in the Person entity, but this might adversly effect performance.
- If you are using JPA 2.0, the simplest way is to use an OpenEntityManagerInView interceptor. Then you can use JSON Jackson to json-ify the Person entity completely and return the JSON to the view.
- If option#1 and option#2 is not feasible, you should try loading the actual collection objects rather than proxies for the same. What should be done is, for each of the collections (lets say collection A) call A.get(0).someGetter() before the session/transaction is closed.This will load the actual instances of objects in the collection A. This should be done for each of the collections. You can have a specific method to do so under certain cases, such as this case.
- Convert the complete Person entity into some other type of object, such as JSON (as you are using ajax here) before the session/transaction is closed. To do this iterate over all the objects in all the collections and fill them up in a JSON object and return the same.
LazyInitializationException occurs when trying to fetch collection from the entity which is already detached from the session.
For that you have to reattach the entity i.e making it managed. First verifying whether objects is associated with session or not.
contains(Object object) : Check if this instance is associated with this Session.
Based on object state, you can read its state again when needed & thereafter can fetch related collections.
refresh(Object object) : Re-read the state of the given instance from the underlying database.
精彩评论