如何在Spring Data Graph中保持Neo4J NodeEntity之间的关系,而不需要两次调用persist

时间:2011-11-10 15:32:46

标签: spring neo4j spring-data spring-data-graph

如果删除第一个persist(),则下面的测试失败。为什么我需要持久化NodeEntity才能实例化Set?有没有更好的方法来做到这一点?我不想比nessesary更频繁地写入数据库。

 @Test
public void testCompetenceCreation() {
    Competence competence = new Competence();
    competence.setName("Testcompetence");
    competence.persist(); //test fails if this line is removed
    Competence competenceFromDb = competenceRepository.findOne(competence.getId());

    assertEquals(competence.getName(), competenceFromDb.getName());

    Education education = new Education();
    education.setName("Bachelors Degree");
    competence.addEducation(education);
    competence.persist();


    assertEquals(competence.getEducations(), competenceFromDb.getEducations());
}

如果删除提到的行,则会发生以下异常:

抛出

java.lang.NullPointerException
at com.x.entity.Competence.addEducation(Competence.java:54)

Competence.class:

@JsonIgnoreProperties({"nodeId", "persistentState", "entityState"})
@NodeEntity
public class Competence {

    @RelatedTo(type = "EDUCATION", elementClass = Education.class)
    private Set<Education> educations;

    public Set<Education> getEducations() {
        return educations;
    }

    public void addEducation(Education education) {
        this.educations.add(education);
    }
}

Education.class

@JsonIgnoreProperties({"nodeId", "persistentState", "entityState"})
@NodeEntity
public class Education {

    @GraphId
    private Long id;

    @JsonBackReference
    @RelatedTo(type = "COMPETENCE", elementClass = Competence.class, direction = Direction.INCOMING)
    private Competence competence;

    @Indexed
    private String name;

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

1 个答案:

答案 0 :(得分:1)

您在运行什么版本的SDN?

因为直到第一个持久化实体被分离并且AJ不处理字段(比如创建托管集)。 Persist创建节点,将节点连接到实体,从那时起,直到事务提交,您的实体被附加,所有更改都将被写入。

它只会在提交时写入数据库,因此不必担心写入太多。所有其他更改将仅保留在内存中以进行交易。也许您还应该使用@Transactional注释测试方法。

您可以为此创建JIRA问题吗?这样就可以提供一致的处理。 (问题是当你自己初始化集合时它可能也会抱怨。)

另外两件事:

  • 由于您在Education&lt; - Competence之间的关系可能相同,只是在另一个方向导航,您必须在注释中提供相同的 type名称。
  • e.g。教育及LT - [:提供] -Competence

  • 如果你不调用persist,你的实体将不会被创建,然后通过返回null

  • 来创建findOne