Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: One to Many getId() not to fetch compete object

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?

like image 953
Akashdeep Saluja Avatar asked Dec 14 '25 15:12

Akashdeep Saluja


2 Answers

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.

like image 109
v.ladynev Avatar answered Dec 17 '25 04:12

v.ladynev


You should write a HQL query and select only the ids.

like image 20
Sándor Juhos Avatar answered Dec 17 '25 04:12

Sándor Juhos