java - 选择动态层次结构的 jpa 自引用中的所有子子详细信息

标签 java hibernate jpa orm playframework

我正在使用带有 java jpa mysql 的 play 2.3.x 并陷入数据库问题。我有实体 Executive,我使用 One-to-Many 关系进行 self 引用code>(我使用这个是因为我想创建一个动态分层数据库)。

Executive.java模型

@Entity
public class Executive {

    @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Constraints.Required
    private String full_name;

    @ManyToOne
    private Executive upperExecutive;

    @OneToMany(mappedBy="upperExecutive")
    private Collection<Executive> lowerExecutives;

    private String type;

}
 

因此,给定一个执行人员的 ID,我想找到它的所有子用户,因此我做了一个简单的选择,例如

public static Executive getHierachyUser(Long id) {

    Executive executive = (Executive)JPA.em().createQuery("select e from Executive e where e.id=:id").setParameter("id",id).getSingleResult();

    return executive;
}

但是在 View 中我不知道层次结构有多长,所以我不知道如何获取某个执行官以下的所有执行官。所以如果我的层次结构是

hierarchy

在我看来,我正在传递找到的执行对象并执行 getlowerExecutive() 但我怎么知道我必须在 user4 之后继续执行它并在 user6 之后停止执行它。我现在在做什么

 <ol>
        @for(executive <- executiveList) {
           <li>@executive.getFull_name

               @if(executive.getLowerExecutives.size()>0){
                   <ol>
                       @for(executive2 <- executive.getLowerExecutives) {
                           <li>@executive2.getFull_name</li>
                       }
                   </ol>
               }

           </li><br><br>
        }
       </ol>

这将如何在其他表中工作,例如我有与执行人员具有一对多关系的 ExecutiveRecord 实体。用户如何查看他的较低执行人员历史记录?

是否还有其他方式让用户可以查看其下方的所有主管?

提前致谢。

谢谢

最佳答案

如果您想显示整个层次结构,您可以简单地递归遍历它,直到没有剩余的子级可供提取。

  1. 确保始终初始化您的集合:

    @OneToMany(mappedBy="upperExecutive")
    private Collection<Executive> lowerExecutives = new ArrayList<>();
    
  2. 获取根执行程序后,您可以递归地遍历整个层次结构:

    public void fetchChildren(Executive executive) {
        if(!executive.lowerExecutives.isEmpty()) {
            for(Executive lowerExecutive : executive.lowerExecutives) {
                fetchChildren(lowerExecutive);
            }
        }
    }
    

这样,当您必须在 UI 中显示层次结构时,层次结构将被初始化,您必须使用相同的递归算法来显示所有子级。

关于java - 选择动态层次结构的 jpa 自引用中的所有子子详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31289662/

相关文章:

java - 绑定(bind)异常 : Address already in use even with unique port

java - sql和java查询数据

java - 使用 JPA/hibernate 在数据库表中手动维护实体行版本/历史记录

java - JPA (hibernate) 按字段映射子对象

mysql - JPQL jpa (@Query) for update column with binary operator mysql query 是什么?

Java代码在Java环境中运行正常,但在Android环境中抛出错误

java - 树莓派上的 Tomcat 无法初始化 gnu.io.CommPortIdentifier

mysql - JDBCExceptionReporter [错误] 字段 'id' 没有默认值

java - 如何使用Spring-Batch批量插入?

java - Jpa,Seam 更新实体