"whats the safest way to remove lazy initialization proxies generated by hibernate?" Code Answer


Proxies are generated so that Hibernate can intercept calls to uninitialized associations and try fetching them on-demand.

The LazyInitializationException is a code smell. You get it because you haven't properly initialized all the required entity associations prior to closing a Session. Switching to EAGER associations is also a bad idea because the fetching policy is a query responsibility.

Try to reduce the number of associations if you don't need them and use queries instead. You can build an application with just many-to-one associations (mirroring the FK relations) and instead of one-to-many associations you can have DAO methods.

As for this statement:

I would like to keep the Parent/Child relationship but when I parse through the Parent Object I don't want to fetch the child elements.

If you keep the Parent/Child relationship you always need to load the association prior to using it. Trying to remove the proxies sounds like you are trying to hack a solution instead of properly design your application layers.

So Proxies are fine and they allow you to improve the application performance, because you don't always fetch all associations when you try to access a root entity.

To disable proxies you just have to annotate your entities with the Proxy annotation:

By Matt Stevens on August 14 2022

Answers related to “whats the safest way to remove lazy initialization proxies generated by hibernate?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.