我有一个Item实体
@Entity
public class Item {
@Id
private Long id;
@ManyToOne
private Item parentItem;
private String name;
private String number;
// getters & setters
}
我想要一个用以下规则生成数字的函数:
- 根元素得到一个像1这样的数字。2
- child元素扩展它的父编号,得到一个类似1.1的数字。1.2
- 其他子元素也扩展了它们的父编号,如1.1.1。1.1.2
- 后代级别没有限制
只需遍历(从左到根(树并连接数字:
@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
}
}