首页 > 解决方案 > 休眠中的递归查询

问题描述

我有具有父/子关系的模型,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: [] 
}
]

感谢帮助。

标签: javahibernatespring-mvcspring-data-jpa

解决方案


您应该尝试像这样的 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();

推荐阅读