java 从父JPA获取所有子级和子级

mu0hgdu0  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(189)

我有一个表TABLE,它可以有相同类型的父表。在Java中,子节点可以访问父节点,但父节点没有子节点列表。
在MySQL中,我能够创建以下查询,它提供父对象的子对象和子对象,但我无法将其转换为JPAJava。
如何翻译此查询:

SELECT * 
FROM TABLE AS T1 
INNER JOIN 
  (SELECT id FROM TABLE WHERE TABLE.parentId = 966) AS T2 
  ON T2.id = T1.parentId OR T1.parentId = 966 
GROUP BY T1.id

在java语言中,使用Criteria builder和Criteria Query,我已经尝试过这样的东西:

CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TABLE> cq = cb.createQuery(TABLE.class);
    Root<TABLE> tABLE= cq.from(TABLE.class);

    Predicate result = cb.conjunction();

    Join<TABLE, TABLE> TABLEJoin = tABLE.join("parent", JoinType.INNER);
    result = cb.and(result, cb.equal(genericLocationJoin.get("parent"), location));
em.createQuery(cq.select(tAble).where(result)).getResultList();

但这只给出了直接子项,没有给出子项。
谢谢你的帮助。
实体:

@Entity
@Table(name = "table")
public final class TABLE {

    @Column(nullable = false, unique = true, length = 20)
    private String externalId;

    @Column(nullable = false, length = 50)
    private String name;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "parentId", nullable = true)
    private TABLE parent;
}
ia2d9nvy

ia2d9nvy1#

您可以在域模型中处理这个问题,方法是使关系是双向的,并编写一个递归方法来遍历树。这样做的一个好处是,它将处理任何级别的孩子。
这看起来像下面这样,然后对于任何你可以做的示例:

SomeEntity e = //;
e.getChildren(); //only direct children
e.getAllChildren(); //all children

实体:

@Entity
@Table(name = "some_entity")
public final class SomeEntity {

    @Column(nullable = false, unique = true, length = 20)
    private String externalId;

    @Column(nullable = false, length = 50)
    private String name;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "parentId", nullable = true)
    private SomeEntity parent;
    
    @OneToMany(mappedBy = "parent")
    private List<SomeEntity> children; //or Set<>
    
    //returns direct children
    public List<SomeEntity> getChildren(){
        return children;
    } 
    
    //returns all children to any level
    public List<SomeEntity> getAllChildren(){
        getAllChildren(this);
    }
    
    //recursive function to walk the tree
    private List<SomeEntity> getAllChildren(SomeEntity parent){
        List<SomeEntity> allChidren = new ArrayList<>();
        
        for(SomeEntity child : parent.getChildren()){
            allChildren.add(child);
            allChildren.addAll(getAllChildren(child);
        }
        
        return allChildren;
    }
}

相关问题