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中编写递归代码.提前致谢.
不要在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)
归档时间: |
|
查看次数: |
3833 次 |
最近记录: |