Neo4j OGM how to delete relationship

本秂侑毒 提交于 2019-12-23 05:41:15

问题


I have two neo4j-OGM node entities connected with property-less relationship like so:

@NodeEntity
public class User {

    @Relationship(type = RelationshipNames.USER_DEVICES, direction = Relationship.UNDIRECTED)
    private Set<Device> devices;

}

@NodeEntity
public class Device {

    @Relationship(type = RelationshipNames.USER_DEVICES, direction = Relationship.UNDIRECTED)
    private User user;

}

When I add a device to a user and then perform save, i get this graph:

Later on, when i both remove the device from user device set and save it, and set device user to null and save it, I still have the same graph, meaning the relationship between the device and user still exist.

I'm i doing something wrong? Is there a way to delete it?


回答1:


Without seeing the code you've written that saves these objects, its not easy to diagnose your problem. However, I would suggest two things.

First, I would ensure that the addition and removal of user-device references in your domain model is managed by the domain model itself. In other words, provide a behaviour on the User class that keeps the Device object consistent, whenever a Device is added or removed.

addDevice(Device device) {
    if (device.user() != null) {
        device.user().removeDevice(device)
    }
    device.setUser(this)
    devices.add(device);
}

Obviously you'd need to write an equivalent removeDevice() as well. This will ensure both objects are properly sync'd if you manage them via the User. If you also intend managing them from the Device as well, you should write an equivalent updateUser() method on the Device class that achieves the same effect.

The point is: get your domain model to do this work. Its much easier to reason about (and test) and you don't need to keep calling getters and setters everywhere in your persistence code just to keep everything in sync.

If, after having made these changes it is still failing, then make the UNDIRECTED relationship INCOMING on one side and OUTGOING on the other (doesn't matter which). If that fixes the problem, it points to a possible bug in the OGM. If which case, please report it here!



来源:https://stackoverflow.com/questions/35391230/neo4j-ogm-how-to-delete-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!