如何从具有父子对关系的自我引用实体中获得部分结果?
我尝试获取整个实体对象,然后将其重构为部分对象。
我也尝试过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,
},
],
},
...
]
我想从结果中删除所有不必要的数据,并希望减少检索映射查询以进行优化。
是否有我可以查找的最佳实践或示例?
最诚挚的问候。
答案 0 :(得分:0)
我按照以下步骤做
[ModelClassName].find.select("field1, field2, ...")
.where
...
....
.findList();
找到的地方
public static final Finder<primaryKeyType, ClassName> find = new Finder<>(ProClassNameducts.class);
请注意,字段名称就像在模型类中一样,而不是在DB中。
希望获得帮助