java - 休眠中的递归查询
问题描述
我有具有父/子关系的模型,1 个类别可以有 1 个/多个子类别
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "category_id")
private int id;
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="parent_id")
private Category parent;
@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "parent_id")
private Set<Category> children;
当我使用 findAll() (spring-data-jpa) 时,我的结果如下
[
{
id:1
children: [
{
id:2
children: []
},
{
id:3
children: [
{
id:4
children: []
}
]
}
]
},
{
id:2
children: []
},
{
id:3
children: [
{
id:4
children: []
}
]
},
{
id:4
children: []
},
{
id:5
children: []
}
]
我想要一个本机查询或类似 (select ... distinct) 的东西,它只返回根类别而不是其他类别的唯一子类别。所以 2、3 和 4 不应成为预期结果的一部分(见下文)。
[
{
id:1
children: [
{
id:2
children: []
},
{
id:3
children: [
{
id:4
children: []
}
]
}
]
},
{
id:5
children: []
}
]
感谢帮助。
解决方案
您应该尝试像这样的 HQL 查询(只是一个示例,未经测试,但希望它为您指明正确的方向):
String hql =
"select c from Category c where c.id not in (" +
"select distinct child.id from Category p join p.children child" +
")";
List<Category> rootCategories =
sessionFactory.getCurrentSession().createQuery(hql).list();
推荐阅读
- wordpress - DNS 迁移后出现 503 错误 AWS ELB
- python - Python:如何按时间格式对字符串进行切片?
- amazon-web-services - 附加 IAM 角色以执行 Lambda 函数的正确 AWS 托管策略
- java - 将二叉搜索树转换为 XML
- java - 如何让 Telegram Bot 从提及中获取用户信息
- python - Pandas中Dataframe的递增列
- c# - 使用 c# 代码创建的 Mongo db 数据库在终端中不可见
- python - 在python中将十进制数转换为任何其他基数(2<=base<=36)
- c# - 如何存储到会话中并显示当前用户信息
- c++ - c++中的for-each循环用于二维数组