Recursion On Database Query使用Hibernate获取分层结果 - Java

dev*_*rsh 6 java sql oracle hibernate recursive-query

我的Oracle数据库中有一个表与子父关系,如 -

在此输入图像描述

我需要的是在Hibernate中以分层方式访问子列表.

  • 当父亲登录时 - 他将儿子当作儿子.
  • 当祖父登录时 - 他得到了儿子,父亲,叔叔.
  • 当超级祖父登录时 - 他得到了儿子,父亲,叔叔和祖父.

我也有一个java实体.

public class relations {
    private String child;
    private String parent;
    public getChild();
    public getParent();
    public setChild();
    public setParent();
}
Run Code Online (Sandbox Code Playgroud)

如何对此进行递归?

我应该通过在SQL中编写一个命名查询来获取列表,或者它可以在java hibernate中实现吗?

我正在寻找的是在java中编写递归代码.提前致谢.

a_h*_*ame 6

不要在Java中进行递归查找.这不会扩展,因为您将向数据库发送大量查询.直接在数据库上使用(单个)递归查询,该查询将更好地执行和扩展.

您没有指定DBMS,但所有现代数据库都支持递归查询.以下是标准ANSI SQL:

with recursive ancestry as (
   select child, parent, 1 as level
   from users
   where parent = 'Grandfather' -- this is the one who logs in
   union all
   select c.child, c.parent, p.level + 1
   from users c
     join ancestry p on p.child = c.parent
)
select child, level
from ancestry
order by level desc;
Run Code Online (Sandbox Code Playgroud)

示例:http://rextester.com/TJGTJ95905


在披露真实数据库后进行编辑.

在Oracle中,您有两种方法可以做到这一点.

"传统"方式是使用connect by哪种是递归查询的更紧凑形式,然后是SQL标准提出的:

select child, level
from users
start with parent = 'Grandfather'
connect by prior child = parent
order by level desc;
Run Code Online (Sandbox Code Playgroud)

也可以在Oracle中使用公用表表达式.但是,即使SQL标准要求关键字recursive是必需的,Oracle也会选择忽略该部分标准,因此您必须将其删除.LEVEL是Oracle中的伪列,只能与其一起使用,connect by因此不能在CTE解决方案中使用:

with ancestry (child, parent, lvl) as (
   select child, parent, 1 as lvl
   from users
   where parent = 'Grandfather'
   union all
   select c.child, c.parent, p.lvl + 1
   from users c
     join ancestry p on p.child = c.parent
)
select child, lvl
from ancestry
order by lvl desc
Run Code Online (Sandbox Code Playgroud)