我有实体:Tweet
和User
。
Tweet
有一个author
,它是User
类的一个实例。用户正在关注其他用户,并跟踪跟踪他的用户:
@ManyToMany
public List<User> following;
@ManyToMany(mappedBy = "following", fetch = FetchType.LAZY)
public List<User> followedBy;
现在我想加载我正在关注的用户推文。我试过这个:
"FROM Tweet AS tweet " +
"JOIN tweet.author as author " +
"JOIN author.followedBy as followedBy " +
"WHERE tweet.author = followedBy AND ? in followedBy ORDER BY dateCreated DESC"
但它不起作用。我很狡猾的查询。
生成的查询,我从抛出的异常中复制了:
SELECT TWEET0_.ID AS ID10_, TWEET0_.AUTHOR_ID AS AUTHOR4_10_, TWEET0_.CONTENT AS CONTENT10_, TWEET0_.DATECREATED AS DATECREA3_10_
FROM TWEET TWEET0_
INNER JOIN USER USER1_ ON TWEET0_.AUTHOR_ID=USER1_.ID
WHERE USER1_.ID IN
(SELECT .[*] FROM USER USER2_, USER_USER FOLLOWING3_, USER USER4_ WHERE USER2_.ID=FOLLOWING3_.FOLLOWEDBY_ID AND FOLLOWING3_.FOLLOWING_ID=USER4_.ID AND USER2_.ID=?)
ORDER BY TWEET0_.DATECREATED DESC LIMIT ?
不幸的是,现在我得到了IllegalArgumentException
:
IllegalArgumentException occured :
org.hibernate.QueryException: illegal attempt to dereference collection [user2_.id.following] with element property reference [id] [select tweet from models.Tweet tweet join tweet.author author where author in (select user.following.id from models.User user where user.id = :id) order by tweet.dateCreated desc]
答案 0 :(得分:1)
我在这里使用子查询:
select tweet from Tweet tweet
join tweet.author author
where author in
(select following.id from User user join user.following following where user.id = :id)
order by tweet.dateCreated desc