简体   繁体   English

在冬眠/休眠中获取n级深层关系

[英]fetching n level deep relation in hibernate/gorm

I have implemented a Category domain which supports n level deep nesting. 我实现了一个类别域,它支持n级深度嵌套。

The Category table contains a parent_id which is nothing but a id of Category table only. 类别表包含一个parent_id,仅是类别表的ID。

public class Category {

String name;
//Reference to parent category
Category parentCategory;
//Child categories if this Category is a parent (Should I keep this in domain or remove it?)
Set categories;
}

A > B > C A> B> C

M > N > O > P > Q M> N> O> P> Q

The above hierarchies can be created by setting id of A as parent_id of B, id of B as parent_id of C id of M as parent_id of N, id of N as parent id of O and so on.. 可以通过将A的id设置为B的parent_id,将B的id设置为M的C id,作为N的parent_id,将N的id设置为O的父ID来创建上述层次结构。

Now I want to display a tree like structure of all the categories (using jsTree). 现在,我想显示所有类别的树状结构(使用jsTree)。 What will be the best way to fetch the data? 什么是获取数据的最佳方法?

You can use hasMany relationship to self for the child sub-categories. 您可以将hasMany关系与self用作子子类别。

public class Category {
   String name;
   //Reference to parent category
   Category parentCategory;
   static hasMany = [subCategories: Category]
}

Now you can either do a lazy fetch on the parent to get the child elements by using a '.' 现在,您可以通过使用“。”对父对象进行延迟获取以获取子元素。 operation on the parent OR use a criteria to fetch all the child elements eagerly (provided this is inexpensive). 对父级的操作或使用条件急切地获取所有子级元素(前提是这样做便宜)。

Note: We would only need the parentCategory in order to move up the tree from leaf node towards the root. 注意:我们只需要parentCategory即可将树从叶节点移到根。 If only one way traversal is needed then the hasMany mapping should be sufficient. 如果只需要一种遍历,则hasMany映射就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM