Search code examples
javaneo4jrelationshipstack-overflowneo4j-ogm

Stackoverflow-Exception while loading RelationshipEntity in OGM


I have the following classes:

@NodeEntity
public class Item{
  //...
}

@RelationshipEntity(type = "HAS")
public class HasRelation{
  //...
  @StartNode
  private User user;

  @EndNode
  private Item item;
}

@NodeEntity
public class User{
  //...
  @Relationship(type="HAS")
  private Set<HasRelation> has;
}

So now I have a User Sven with ID 1 having an Item Hammer in the Database and want to load it. When I call the OGM session.load(User.class, 1) I always get an Stackoverflow-Exception, because the User hold a Relationship, holding the User, holding a relationship, and so on. This feels like the wrong way to use OGM for me and I don't want to restrict the Depth by which I load to 0. However the OGM specification tells me, that there is no other way, since the RelationshipEntity needs a Start- and EndNode and has to be referenced in one of those. So I don't see a way to prevent this Exception other than resticting the Loading-Depth to 0. Is there a better way?


Solution

  • You are exposing the data as JSON. The converter also needs to traverse the 'object tree' and this causes the stackoverflow.

    The solution is simple: You are defining an outgoing relationship in the User class so this object does not need to be visited again when the jackson lib hits the relationship.

    @RelationshipEntity(type = "LIKES")
    public class LikedBook {
    
    @Id
    @GeneratedValue
    private Long id;
    
    private String how;
    
    @StartNode
    @JsonIgnore // <- "do not go back"
    private User user;
    
    @EndNode
    private Book book;