问题
Is is possible to pls advice me how to go about.. doing a Same Entity Relationship..
For ex. Entity(class Person) relatesTo Entity(class Person).
CODE:
@NodeEntity
public class Person
{
@GraphId @GeneratedValue
private Long id;
@Indexed(indexType = IndexType.FULLTEXT, indexName = "searchByPersonName")
private String personName;
@Fetch @RelatedTo(type = "CONNECTS_TO", direction = Direction.BOTH)
private Set<ConnectedPersons> connectedPersons;
public ConnectedPersons connectsTo(Person endPerson, String connectionProperty)
{
ConnectedPersons connectedPersons = new ConnectedPersons(this, endPerson, connectionProperty);
this.connectedPersons.add(connectedPersons); //Null Pointer Here(connectedPersons is null)
return connectedPersons;
}
}
CODE:
@RelationshipEntity(type = "CONNECTED_TO")
public class ConnectedPersons{
@GraphId private Long id;
@StartNode private Person startPerson;
@EndNode private Person endPerson;
private String connectionProperty;
public ConnectedPersons() { }
public ConnectedPersons(Person startPerson, Person endPerson, String connectionProperty) { this.startPerson = startPerson; this.endPerson = endPerson; this.connectionProperty = connectionProperty;
}
I am trying to have a Relationship to the same class.. i.e. Persons connected to the Person.. When I invoke a Junit test :
Person one = new Person ("One");
Person two = new Person ("Two");
personService.save(one); //Works also when I use template.save(one)
personService.save(two);
Iterable<Person> persons = personService.findAll();
for (Person person: persons) {
System.out.println("Person Name : "+person.getPersonName());
}
one.connectsTo(two, "Sample Connection");
template.save(one);
I get Null pointer when I try to do one.connectsTo(two, "Prop");
Please could you tell where am I going wrong?
Thanks in advance.
回答1:
One other thing besides the missing initialization of the Set is that the class ConnectedPersons is a @RelationshipEntity. But in your class Person you are using it with the @RelatedTo annotation as if it were a @NodeEntity. You should use the @RelatedToVia annotation in the Person class instead.
回答2:
You are getting null pointer exception in the below code because you haven't initialized the connectedPersons
collection.
this.connectedPersons.add(connectedPersons); //Null Pointer Here(connectedPersons is null)
Initialize the collection as shown below
@Fetch @RelatedTo(type = "CONNECTS_TO", direction = Direction.BOTH)
private Set<ConnectedPersons> connectedPersons=new HashSet<ConnectedPersons>();
来源:https://stackoverflow.com/questions/18413242/neo4j-same-entity-relationship-persistence-issue