在我的 Jboss7 Java EE 6 Web 应用程序中,我需要管理一个简单的“类别”实体的树结构,如下所示:
@Entity
@Table(name="categorie")
@NamedQueries({
@NamedQuery(name="selezionaTutti", query="select c from Categoria c left join fetch c.children left join fetch c.parent")
})
public class Categoria implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String nome;
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
@JoinColumn(name = "parent_id")
private List<Categoria> children = new LinkedList<Categoria>();
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "parent_id",insertable=false,updatable=false)
private Categoria parent;
... //various getter, setter, and so on
}
命名查询一次加载我的整个(小)树,第一次,然后它停留在持久性上下文中。
然后我想“探索”这棵树,所以我得到根节点并将其传递给这个函数:
private List<Categoria> getAlberoCategorie(Categoria root, int profondita) {
List<Categoria> tmpList = new ArrayList<Categoria>();
root.setProfondita(profondita);
if ( root.getParent() != null ) {
tmpList.add(root);
}
if (!root.getChildren().isEmpty()) {
profondita++;
for (Categoria figlia : root.getChildren()) {
tmpList.addAll(getAlberoCategorie(figlia,profondita)); // this line generates the stack overflow!!!
}
}
return tmpList;
}
异常的确切堆栈跟踪是:
java.lang.StackOverflowError org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:112) org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:137) org.hibernate.collection.internal.PersistentBag .isEmpty(PersistentBag.java:249) it.trew.data.CategoriaFacade.getAlberoCategorie(CategoriaFacade.java:59)
在我的本地机器上,确实一切正常。在小型测试服务器上,读取类别时崩溃!
我怎样才能改善我的功能?