【问题标题】:Recursion On Database Query to get hierarchical result using Hibernate - Java使用 Hibernate 对数据库查询进行递归以获取分层结果 - Java
【发布时间】:2017-02-16 11:43:53
【问题描述】:

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

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

  • 当父亲登录时 - 他得到儿子作为孩子。
  • 当祖父登录时 - 他得到儿子、父亲、叔叔。
  • 当超级祖父登录时 - 他得到儿子、父亲、叔叔和祖父。

我也有一个 java 实体。

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

如何对此进行递归?

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

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

【问题讨论】:

  • 请在link查看答案

标签: java sql oracle hibernate recursive-query


【解决方案1】:

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

您没有指定 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

【讨论】:

    猜你喜欢
    • 2011-09-22
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 2014-01-25
    • 1970-01-01
    相关资源
    最近更新 更多