针对自引用对象的多对多关联的HQL查询

时间:2013-06-12 11:36:48

标签: hibernate orm many-to-many jpa-2.0 hql

我有这个课程:

    @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

如果我需要用户的所有朋友,我可以通过简单地调用getAllFriends()来获取它们。 但我想为最多返回的朋友添加一些限制。所以我想用HQL选择所有朋友。我想要这样的东西(我的hql不正确,只是为了表明这个想法):

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();

是否可以创建这样的查询?

更新:我的SQL查询符合我的要求。也许有人可以帮我翻译成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);

1 个答案:

答案 0 :(得分:2)

HQL不支持UNION子句(有问题:https://hibernate.atlassian.net/browse/HHH-1050),所以这有点困难,但我认为你可以这样做:

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
    )