【问题标题】:How to delete a relationship of a neo4j node in spring data如何在spring数据中删除neo4j节点的关系
【发布时间】:2021-09-18 18:46:32
【问题描述】:

我有用户节点并且彼此之间有联系关系。 user1 有两个联系人 user2 和 user3。现在我想从联系人中删除 user2。下面是一段关于联系人关系的代码sn-p。

@Node
public class User{
...Id and different properties
@Relationship(type = "CONTACT")
public Set<User> contacts = new HashSet<>();
}

现在,当我删除关系并保存节点时,它会显示以下消息:

WARN 38461 --- [nio-8080-exec-2] o.s.d.n.c.m.DefaultNeo4jIsNewStrategy : 具有指定 id 的 com.talkkia.api.entity.User 类的实例将始终被视为没有版本属性的新实例!

删除关系的代码在这里:

@Transactional
@Override
 public String deleteContact(String mobile1, String mobile2) {
        Optional<User> user1 = userRepository.findOneByMobile(mobile1);
        Optional<User> user2 = userRepository.findOneByMobile(mobile2);
        if(user1.get().getContacts().contains(user2.get())){
            user1.get().getContacts().remove(user2.get());
            System.out.println(user1.get().getContacts());
            userRepository.save(user1.get());
            return user2.get().getName() + " has been deleted from your contact.";
        }
        
        return user2.get().getName() + " can't be deleted from contact.";
    }

【问题讨论】:

    标签: spring spring-boot neo4j spring-data spring-data-neo4j


    【解决方案1】:
    @Query("MATCH(user1:User {mobile: $mobile1})-[c:CONTACT]-(user2:User {mobile:$mobile2}) DETACH DELETE c")
    public String deleteContact(String mobile1, String mobile2);
    

    我认为上述解决方案非常简单且性能良好。 @meistermeier 点也是有效且可观的。

    【讨论】:

      【解决方案2】:

      警告信息正是导致您面临的情况的原因。 因为您使用的是分配的、手动提供的 id,所以 Spring Data Neo4j 无法区分对象是否是新的。 解决方案是在实体中提供@Version 字段(如@Version Long version)。 如果元素来自数据库还是新创建的,则可以从这个 SDN 中获取信息。

      由于错误地假定了实体的新状态,因此不会删除任何关系,因为持久性逻辑中没有必要这样做。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-14
        • 2012-12-24
        • 2014-05-24
        • 1970-01-01
        相关资源
        最近更新 更多