StackOverflowError when trying to explore a hierarchy
fabio.bozzo May 16, 2012 4:38 AMIn my Jboss7 Java EE 6 web application, I need to manage a tree structure of simple "category" entities like that:
@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
}
The named query load my whole (little) tree all at a time, the first time, then it stays in the persistence context.
Then I want to "explore" the tree, so I get the root node and pass it to this function:
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;
}
The exact stack trace of the exception is:
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)
In my local machine, all works fine indeed. On a small test server, it crashes when reading categories!
How can I improve my function?