Michael Jarret
Michael Jarret

Reputation: 103

Node Entity needs to be found again after adding relationships (neo4j/java/spring)

I've used the @NodeEntity annotation for a class topic. In Topic there is the following: (For sake of brevity, I've narrowed the error down, so I'm only writing up the relevant parts of the code.)

public class Topic {

    ...

    @RelatedTo(type = "MADE_OF", direction = Direction.OUTGOING)
    public Set<Topic> madeOf;

    @RelatedTo(type = "MADE_OF", direction = Direction.INCOMING)
    public Set<Topic> partOf;

}

Now, this gets instantiated elsewhere like:

    Topic myTopic = new Topic();
    madeOf.addAll(some list of topics with empty partOf already in the graph);
    myTopic = template.save(myTopic());

Now, if I check over the set of topics in myTopic.madeOf, all of them are empty, even though they should all include myTopic. Alternatively, if I do:

    Topic myTopic = new Topic();
    madeOf.addAll(some list of topics with empty partOf already in the graph);
    myTopic = template.save(myTopic());
    myTopic = template.findOne(myTopic());

and now check the same thing, everything is as it should be. Obviously finding this entity over and over slows down my code considerably. The same behavior occurs even if I add the relationships to the Neo4JTemplate explicitly with template.createRelationshipBetween(...).

Any ideas?

Upvotes: 0

Views: 190

Answers (2)

tstorms
tstorms

Reputation: 5001

By default with simple mapping enabled, all relationships are lazily fetched. If you want them to be eagerly loaded, use @Fetch on your relationships (thus madeOf and partOf).

@Fetch
@RelatedTo(type = "MADE_OF", direction = Direction.OUTGOING)
public Set<Topic> madeOf;

Upvotes: 0

Gopi
Gopi

Reputation: 10293

After you do a template.save you can do a template.fetch(myTopic.getMadeOf()) to fetch all related topics in one shot and then use the myTopic in usual way

Upvotes: 1

Related Questions