【问题标题】:How to persist relationships between Neo4J NodeEntitys in Spring Data Graph without calling persist twice如何在 Spring Data Graph 中保持 Neo4J NodeEntity 之间的关系而不调用 persist 两次
【发布时间】:2011-12-26 06:58:30
【问题描述】:

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

 @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);
    }
}

教育类

@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;
    }
}

【问题讨论】:

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


    【解决方案1】:

    您运行的是哪个版本的 SDN?

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

    它只在提交时写入数据库,所以不用担心写入太多。所有其他更改将仅保存在您的交易内存中。可能您还应该使用@Transactional 注释测试方法。

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

    另外两件事:

    • 由于您与教育之间的关系相同的type 名称。
    • 例如教育

    • 另外,如果您不调用persist,您的实体将不会被创建,然后通过返回null来查找findOne

    【讨论】:

    • 感谢您的快速回复迈克尔。我现在明白了我需要如何使用持久化,而且您在注释中的关系类型上的注释也是正确的。你能解释一下你想让我在 Jira-issue 中写什么吗?因为据我了解,这不是错误,而是我对 Spring Data Graph 的工作方式没有完全了解:-)
    • 只需创建问题并将其链接到此讨论。作为描述添加 - 以一致的方式初始化集合字段。谢谢
    • 完成!再次感谢您的帮助,非常感谢。 jira.springsource.org/browse/DATAGRAPH-135
    猜你喜欢
    • 1970-01-01
    • 2015-09-04
    • 2016-01-05
    • 2015-08-16
    • 2013-06-08
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    相关资源
    最近更新 更多