I have two entity objects, and have one to many association between them.
Lets call them "One" and "Many". I have set the fetching as "Lazy".
So when I have the "Many" object and try to get Id of "One" object Hibernate internally fetched the complete object. Whereas it can give me Id just on the basis of entity "Many" because it would contain the id of "One". Id of "One" is primary key, and a foreign key in "Many"
many.getOne().getId() //fetches complete "One" object
Is it possible and how?
It is possible, of course. You can use FetchType.LAZY and get an id by this way:
LazyInitializer initializer = ((HibernateProxy) many.getOne()).getHibernateLazyInitializer();
Long id = (Long) initializer.getIdentifier();
It will work only with foreign key associations, not with join table associations.
Or you can use HQL or criteria with a projection, to get an only id.
You should write a HQL query and select only the ids.
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