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.
1 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:
@Proxy(lazy=false)
-
1st of all thanks.. Here is my concern... You said "instead of one-to-many associations you can have DAO methods" . Without one to many associations , I won't be able to use explicit joins for complex queries.... With One to Many association, Lazy Initialization, we are parsing the whole object using Jax-B, the child element will be accessed and it will be fetched.. which is unnecessary & performance loss. Also @Proxy(lazy=false) is not bringing the proxies but it is fetching all the child element.. which is again unnecessary & performance loss....Let me know if you have any suggestion. Jul 30, 2015 at 15:31
-
Well, fetching entities makes sense when you plan to modify them. In your case a projection is more appropriate and will always perform better. You can write a portable natie query and you can fetch just the data you need for your use case. Jul 30, 2015 at 15:41
-
You are actually right... The only option I have is Native query.. but again we have a weird requirement of doing pagination. Pagination will fail when a parent has many children's and we use native query to fetch some elements in parent and some in children's.. Anyway Thanks Really appreciate it.... Jul 30, 2015 at 16:07
-
-
Yes, you can. Use
JOIN FETCH
on theFeatType.EAGER
association, and you'll fetch it using that query. Jun 24, 2022 at 10:50