我有点好奇,有没有办法通过 sql 查询获得连接结果,比如已经映射后代的根实体。因此,如果我在 base 中插入这样的内容:
insert into table test (id, parent_id, some_text) values
(1, null, 'a'),
(2, 1, 'b'),
(3, 1, 'c'),
(4, 2, 'd');
然后通过sql查询
select *
from test t
start with t.id = 1
connect by prior t.id = t.parent_id
order siblings by t.some_text
我会得到
id | parent_id | some_text
1 null a
2 1 b
4 2 d
3 1 c
并按实体
@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
}
它将作为测试列表返回给我。可以通过递归函数获得根和完整的树,但它会在迭代时获得新的查询(如果我有一棵大树,它会很长)。那么有没有一种可能的好方法来通过这个查询获取已经映射后代的这棵树的根(可能扩展/实现一些类/接口,它将处理从 jdbc 到实体的映射)?