Spring Data Neo4J - 创建与现有节点有关系的新节点

Spring Data Neo4J - Create new node with a relationship with an existing node

我需要新建一个classA节点,它与User节点有关系:

@NodeEntity
public class A implements Serializable {

    /**
     * Graph node identifier
     */
    @GraphId
    private Long nodeId;

    /**
     * Enity identifier
     */
    private String id;

    //... more properties ...

    @Relationship(type = "HAS_ADVERTISER", direction = Relationship.OUTGOING)
    private User user;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof IdentifiableEntity)) return false;

        IdentifiableEntity entity = (IdentifiableEntity) o;
        if (!super.equals(o)) return false;

        if (id != null) {
            if (!id.equals(entity.id)) return false;
        } else {
            if (entity.id != null) return false;
        }

        return true;
    }


}


@NodeEntity
public class User implements Serializable {

    /**
     * Graph node identifier
     */
    @GraphId
    private Long nodeId;

    /**
     * Enity identifier
     */
    private String id;

    //... more properties ...


    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof IdentifiableEntity)) return false;

        IdentifiableEntity entity = (IdentifiableEntity) o;
        if (!super.equals(o)) return false;

        if (id != null) {
            if (!id.equals(entity.id)) return false;
        } else {
            if (entity.id != null) return false;
        }

        return true;
    }

}

现在,假设我们有新节点 A 的以下数据:

{
  "id": 1,
  "nodeId": "0001-0001",
  "user": {
           "id": 4,
           "nodeId": "0002-0002",
           "name": null,
           "firstName": null
          }
}

我正在尝试创建节点 A,使新节点 A 与具有 "id":4 和 "nodeId" 的用户的(已经存在的)节点之间存在关系:" 0002-0002”(唯一节点标识符),但用户节点将字段 "name" 和 "firstName" 更新为 null.

我正在使用 GraphRepository 代理来创建它:

@Repository
public interface ARepository extends GraphRepository<A> {


}

有没有办法不用这个更新,只和User节点建立关系?

不,您必须通过 ID 重新加载实体以填充所有缺失值然后保存,或者编写自定义查询。

您可以使用 MERGE 来完成。见 Cypher RefCard

@Repository
public interface ARepository extends GraphRepository<A> {

    @Query("MERGE (a:A {id:aId}})-[:HAS_ADVERTISER]-(u:User {id:{userId}})" +
           "RETURN a")
    public A createAndGetAd(@Param("aId") String aId,
                            @Param("userId") String userId)
    }