0

I'm trying to implement the 'following mechanism' in my Java EE application. I have an Entity Profile that contain, among other things, a List, which is the list of the profiles that the user follows. Le relation is (@OneToMany).

Everithing is fine and sounds great, but i have a problem. A query like that:

Query q = em.createQuery("SELECT p FROM Profile p WHERE p.id =:custId");

Return a Profile p, and so far, no problem. But I noticed that i have the complete access of my following users, and of the following of all my following users, and so on. I see no way out.

I could replace the the List in an array that contain only the id, but only if it is the only choice. Any ideas? Can I "stop" the query by not let her take the Following list of every my Following users ?

  • more information would be required, before we can help. probably your queries are performed with an eager loading strategy, you can google around for how to turn change it to lazy loading. – saljuama Feb 17 '16 at 19:56
  • Yes you have access (assuming session is still open) but default is for them to be fetched on demand. So unless you have explictly configured eager fetch the associations will not be loaded by default. Turn on Sql logging to see what is being fefched. – Alan Hay Feb 17 '16 at 19:56
  • @AlanHay i think you're right. I was scared by the amount of selected data, but I'm not anymore.Thanks for the explaination! – andrea22 Feb 18 '16 at 00:25

1 Answers1

0

I think you need to refactor your API. Don't store the followers list in the profile class, create a service e.g ProfileService and call it whenever you want to access the list of followers for a specific profile.

public class ProfileService {

    public List<Profile> getFollowers(Profile profile) {
       Query q = em.createQuery("SELECT p FROM Profile p WHERE p.id =:custId");
       .....
    }
}
Ervis Zyka
  • 486
  • 1
  • 5
  • 13