I'm using hibernate for persistence. In my data access layer, I specify some parts of the result to be eagerly loaded depending on the scenario.
Now I need to send these result as JAX WS responses.
Is there any way that I can have some cleaner method which will take an entity object, traverse through it, and set null to fields that are not initialized so that hibernate would not throw LazyInitializationException when the object is passed to web service layer.
Or is there any alternatives to solve this issue.
There's such thing as Hibernate#initialize() which you could run in an active session after loading entity, but it will initialize fields/references at the root level of the entity (or collection) you have passed -- in case entity is a Hibernate proxy. As the JavaDoc states:
Note: This only ensures intialization of a proxy object or collection; it is not guaranteed that the elements INSIDE the collection will be initialized/materialized.
Assigning NULL to uninitialized fields is not a good approach as it breaks data consistency (if someone access those fields, then they are expected to return the actual value).
I have the same architecture here and we do the load job in the business layer. There is no way to do this automatically because just you know what data is needed in your ws response. Basically, I have a method that converts a entity model(JPA mapping) to a simple POJO and vice-versa and in this method I resolve which attribute is needed to load.
You could use something like this:
public interface IBusiness<Model, VO> {
public Model toModel(VO vo);
public VO toVO(Model model);
public List<Model> toModelList(List<VO> vos);
public List<VO> toVOList(List<Model> models);
}
You implements this interface on your business layer and solve the lazy problem loading everything you need in this methods.
good luck =)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With