如何从具有父子对关系的自引用实体中获得部分结果?
我试图获取整个实体对象,然后将其重构为部分对象。
我还尝试了 FetchGroup,选择部分列等。
但他们都没有工作。当它检索孩子时,整个对象会发生变化以带来整个实体。
@Entity
public class someClass extents Model {
public String name;
public String code;
@ManyToOne
@JsonBackReference
public Menu parent;
@OneToMany(mappedBy = "parent")
@JsonManagedReference
public Set<someClass> children;
other columns and getters/setters.
}
这是我使用的查找器
public static List<someClass> findInTree() {
find
.query()
.where()
.isNull("parent")
.findList();
}
我可以看到查询正在运行
[info] o.j.StatementLogger - select t0.id, t0.code, t0.name from some_entity t0 where t0.parent_id is null and t0.is_active = Y and to_timestamp('2019-04-04 19:05:54.333', 'yyyy-MM-dd hh24:mi:ss.ff3') between t0.start_date and t0.end_date ;
[info] o.j.StatementLogger - select t0.parent_id, t0.id from some_entity t0 where (t0.parent_id) in (1, 2, 3, 4, 1 ) ;
[info] o.j.StatementLogger - select t0.id, t0.code, t0.name from some_entity t0 where t0.id in (5, 6, 5, 5, 5 ) ;
[info] o.j.StatementLogger - select t0.parent_id, t0.id from some_entity t0 where (t0.parent_id) in (5, 6, 5, 5, 5 ) ;
[info] o.j.StatementLogger - select t0.id, t0.code, t0.name from some_entity t0 where t0.id in (7, 8, 7, 7, 7 ) ;
[info] o.j.StatementLogger - select t0.parent_id, t0.id from some_entity t0 where (t0.parent_id) in (7, 8, 7, 7, 7 ) ;
结果是
"someClass":[
{
"id":1,
"code":"test1",
"name":"test1",
"children":[
],
... rest of columns
},
...
{
"id":4,
"code":"test1",
"name":"test1",
"children":[
{
"id":5,
"code":"test1",
"name":"test1",
"children":[
{
"id":7,
"code":"test1",
"name":"test1",
"children":[
],
},
... rest of columns
],
... rest of columns
},
...
]
我担心递归查询在变得更大时会消耗太多资源。
而且,我想将这种做法用于具有不同关系的其他实体。
预期结果如下所示。
"someClass":[
{
"id":1,
"code":"test1",
"name":"test1",
"children":null,
},
...
{
"id":4,
"code":"test1",
"name":"test1",
"children":[
{
"id":5,
"code":"test1",
"name":"test1",
"children":[
{
"id":7,
"code":"test1",
"name":"test1",
"children":null,
},
],
},
...
]
我想从结果中删除所有不必要的数据,并希望减少检索映射查询以进行优化。
是否有我可以查找的最佳实践或示例?
此致。