Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate deproxy

Tags:

java

hibernate

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.

like image 964
janith Avatar asked Jul 03 '26 02:07

janith


2 Answers

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).

like image 138
Art Licis Avatar answered Jul 04 '26 17:07

Art Licis


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 =)

like image 24
Marcio Barroso Avatar answered Jul 04 '26 16:07

Marcio Barroso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!