java - 递归数据库查询以使用 Hibernate - Java 获取分层结果

标签 java sql oracle hibernate recursive-query

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

enter image description here

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

  • 当父亲登录时 - 他让儿子成为 child 。
  • 当祖父登录时 - 他得到儿子、父亲、叔叔。
  • 当 super 祖父登录时 - 他得到儿子、父亲、叔叔和祖父。

我也有一个 java 实体。

public class relations {
    private String child;
    private String parent;
    public getChild();
    public getParent();
    public setChild();
    public setParent();
}

如何对此运行递归?

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

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

最佳答案

不要在 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;

示例: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;

也可以在 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

关于java - 递归数据库查询以使用 Hibernate - Java 获取分层结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39917848/

相关文章:

c# - Oracle 数据访问 FileNotFound : Oracle. DataAccess.Common.Configuration.Section.xsd

JavaFX - 在自定义节点上设置focusedProperty Listener

java - 使用抽象创建对象失败,可能是我看不到的简单修复

java - 在 Eclipse 控制台中打印唯一的 ASCII 字符

MySQL 查找重复项 + 另一个字段

mysql - 不等于 LeftJoin 的搜索

mysql group_concat 用于左表和右表

java - JSF 2.0 组件

database - Oracle ALL_UPDATABLE_COLUMNS 内容

sql - 关于sql中的日期