简体   繁体   中英

HQL query for Many To Many Associations for self referenced object

I hava this class:

    @Entity
    @Table(name = "USERS")
    public class User {

    @Id
    @Column(name = "USER_ID")
    @GeneratedValue
    private long userId;
    ...
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "FRIENDS", joinColumns = @JoinColumn(name = "USER_ID"), inverseJoinColumns = @JoinColumn(name = "FRIEND_ID"))
        private Set<User> friends;


    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "FRIENDS", joinColumns = @JoinColumn(name = "FRIEND_ID"), inverseJoinColumns = @JoinColumn(name = "USER_ID"))
        private Set<User> friendOf;

   ...
    public Set<User> getAllFriends() {
      allFriends = new HashSet<User>();
      allFriends.addAll(friends);
      allFriends.addAll(friendOf);
      return allFriends;
}
   // getters and seters

If I need all friend of a User I can get them by simply calling getAllFriends(). But I want to add some restriction to the maximum number of returned friends. So I want to select all friends using HQL. I want something like this (my hql is incorrect, just to show the idea):

String hql = "Select u FROM User u inner join u.friendOf fof WHERE fof.userId = :userId inner join u.friends fs WHERE fs.userId = :userId";
    Query query = sessionFactory.getCurrentSession().createQuery(hql);
    query.setParameter("userId", userId);
    List<User> results = query.setMaxResults(maxResults).setFirstResult(firstResult).list();

Is it possible to create such a query?

UPDATE: I have SQL query whiсh fits my requirements. Maybe someone can help me to translate it to HQL?

select * from users where user_id in (
select 
 (case  
  when user_id = :userId then friend_id 
  else user_id 
 end) as id
from friends
where user_id = :userId or friend_id = :userId);

HQL does not support UNION clause (there is open issue: https://hibernate.atlassian.net/browse/HHH-1050 ), so this is a little bit harder, but i think you can do something like this:

select u
from User u
where u.userId in (
        select fr.userId
        from User u1
        inner join u1.friends fr
        where u1.userId = :userId
    ) 
    or u in (
        select fr.userId
        from User u2
        inner join u2.friendOf fr
        where u2.userId = :userId
    ) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM