【问题标题】:Spring Data Neo4J - Create new node with a relationship with an existing nodeSpring Data Neo4J - 创建与现有节点有关系的新节点
【发布时间】:2016-04-02 16:05:55
【问题描述】:

我需要新建一个A类的节点,和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 与具有“id”:4 和“nodeId”:“0002-0002”(唯一节点标识符),但用户节点将字段“name”和“firstName”更新为null

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

@Repository
public interface ARepository extends GraphRepository<A> {


}

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

【问题讨论】:

    标签: neo4j spring-data-neo4j spring-data-neo4j-4


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回复!
    【解决方案2】:

    您可以使用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)
        }
    

    【讨论】:

      猜你喜欢
      • 2016-05-01
      • 1970-01-01
      • 2017-05-08
      • 1970-01-01
      • 2015-11-07
      • 2015-09-07
      • 2018-11-23
      • 1970-01-01
      • 2014-01-04
      相关资源
      最近更新 更多