【问题标题】:How to number a tree entity object that extends parent's number?如何对扩展父编号的树实体对象进行编号?
【发布时间】:2021-07-22 19:39:40
【问题描述】:

我有一个 Item 实体

@Entity
public class Item {

  @Id
  private Long id;

  @ManyToOne
  private Item parentItem;

  private String name;

  private String number;

  // getters & setters

}

我想要一个生成具有以下规则的数字的函数:

  • 根元素有一个数字,例如 1. 2。
  • 子元素扩展它的父元素并得到一个类似 1.1 的数字。 1.2
  • 其他后代元素也扩展了它们的父编号,如 1.1.1。 1.1.2
  • 后代级别没有限制。

【问题讨论】:

    标签: java hibernate jpa recursion


    【解决方案1】:

    只需遍历(从叶到根)树并连接数字:

    @Entity
    public class Item {
    
      @Id
      private Long id;
    
      @ManyToOne
      private Item parentItem;
    
      private String name;
    
      private String number;
    
      String getHierarchy(){
        return this.parentItem != null ? 
                 this.parentItem.getHierarchy() + " . " + this.number :
                 this.number
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-20
      • 2019-12-25
      • 2011-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多