**Background**

I have a table with columns *id, imageId, propertyId*. 

There could be many images associated with a single property and there could be many properties associated with a single image.

`imageId - many-to-many - propertyId`

I have a list of propertyIds and I want to find out all the images associated with all the propertyIds **using Hibernate**.

**Problem.**

Just now I pick one property at a time and using the Criteria API find all the imageIds associated with this propertyId, I obtain a list of imageIds. I use this list of imageIds in the next query and say 

`select imageIds where imageId in (imageIds obtained in previous step) where propertyId = x`

So effectively, the number of queries hitting the DB would equal to the number of propertyIds. I don't think this is a good solution, having to hit the database n times, I tried using Detached Query but did not succeed. Is there a better solution?

Also, when I finally obtain the list of imageIds, is it a good idea (let us not take into account the number of results) to store it in the user session and paginate OR is it a good idea to repeat the entire process OR shall I consider storing it in the DB all for the purpose of pagination?