I have an entity named PetOwner. PetOwner has a list of Pets. And each Pet has a Store (ie: the store this pet came from). Pet is an abstract class and getting a concrete version does lots of joins (@Inheritance(strategy = InheritanceType.JOINED)
). I want to have a method on PetOwner with this signature:
Set<Store> getAllStores();
The problem is that loading the list of Pets is very slow and in fact unnecessary to get the list of Stores. When I call getAllStores
, I'd like it to run SQL like this:
SELECT DISTINCT store_id
FROM pet
WHERE petowner_id = x;
But if I implement it like this:
Set<Stores> stores = //
for (pet : pets)
stores.add(pet.getStore());
return stores;
It'll pull in all the Pets and be very slow. So how can I prevent it from pulling in all the Pets? Ideally, I do want this method on the PetOwner object because I think the code is more object oriented that way.
Also, there are other methods inside PetOwner where I do need to load the list of Pets even though it's slow. But I don't always call it, that's why I'd like just this method to avoid loading the pet list.