简体   繁体   中英

How to get root by recursive oracle query in Hibernate

I'm a little curious, is there a way to get result of connect by sql query like root Entity with already mapped descendants. So if I'm insert in base something like this:

insert into table test (id, parent_id, some_text) values
(1, null, 'a'),
(2, 1, 'b'),
(3, 1, 'c'),
(4, 2, 'd');

then by sql query

select *
from test t
start with t.id = 1
connect by prior t.id = t.parent_id
order siblings by t.some_text

I will get

id | parent_id | some_text
 1        null           a
 2           1           b
 4           2           d
 3           1           c

and by entity

@Entity
@Table(name = "test")
public class Test {
    @Id
    @Column(name = "id")
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    private BigInteger id;

    @Column(name = "parent_id")
    private BigInteger parent_id;

    @Column(name = "some_text")
    private String someText;

    @OneToMany(mappedBy = "parent")
    private Set<Test> descendants;

    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Test parent;
    // getters and setters
}

it will back to me as list of Test. It possible to get root and full tree by recursive function, but it will get new query on iteration (it will very long if I have a big tree). So is there a possible good way to get root of this tree with already mapped descendants by this query (maybe extend/implement some class/interface which will process mapping from jdbc to entity)?

you can use CONNECT_BY_ROOT unary operator. See docs

select t.*, connect_by_root id
from test t
start with t.id = 1
connect by prior t.id = t.parent_id
order siblings by t.some_text

BTW: this has nothing to do with Hibernace. This is purely Oracle specific solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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