我有两个 hibernate 实体用户和博客。用户可以对多个标签感兴趣。博客可以属于多个标签。对于用户来说,如何找到属于用户感兴趣的标签的博客?
我需要类似的东西
Select * from Blog where Blog.Tags IN User.Tags
除了 SQL 或 HQL 不允许在 IN 子句中进行此类比较
我目前使用的解决方案是:
- 生成一个 VIEW USER_BLOGS,它是 连接表 USER_TAGS 和 BLOG_TAGS。
为 View 定义实体 UserBlog 并使用它来过滤博客 HQL 查询:
Select * from Blog where Blog.id IN (Select blog_id from UserBlog where user_id = "CurrentUser")
我确信这是一个常见的情况。是否有一个纯粹的 Hibernate 或 HQL 解决方案?
最佳答案
您正在寻找这样的东西吗?
select b.*
from blog b
join blog_tags bt on bt.blog_id = b.id
join user_tags ut on ut.tag = bt.tag
where ut.user_id = (this_user)
与评论相反,我相信 HQL 确实允许显式连接(我可能是错的,但请参阅 http://www.hibernate.org/hib_docs/reference/en/html/queryhql-joins.html )。在任何情况下,都可以在没有显式连接的情况下完成:
select b.*
from blog b, blog_tags bt, user_tags ut
where ut.user_id = (this_user)
and bt.blog_id = b.id
and ut.tag = bt.tag
关于java - 如何获得两个一对多关联的加入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/635630/