在Spring Data Neo4J中保存关系的正确方法是什么?

时间:2015-04-15 14:15:29

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

使用Spring Boot和Neo4J,我创建了两个@NodeEntity。它们是UserRight。在我的模型中,当您在User和Right之间创建关系时,我将其称为Privilege

我无法保存@RelationshipEntityPrivilege(来自@NodeEntity之内或RelationshipEntity)。

示例代码

User.java(由UserRepository接口支持扩展GraphRepository)

@NodeEntity
public class User {

    @Autowired Neo4jTemplate template;

    @GraphId Long id;
    String fullName;
    @Indexed(unique=true) String email;

    @Fetch @RelatedTo(type="HAS_RIGHT")
    Set<Right> rights;

    public void addRight(Right r) {
        Privilege p = new Privilege (this, r)
        template.save(p)  // This always throws a NullPointerException
    }

    /*** Getters and Setters ***/

}

Right.java(由接口RightRepository支持扩展GraphRepository)

@NodeEntity
public class Right {

    @GraphId Long id;
    String name;

    /*** Getters and Setters ***/

}

Privilege.java(不受存储库界面支持) - 问题类

@RelationshipEntity(type="HAS_RIGHT")
public class Privilege {

    @Autowired
    Neo4jTemplate template; // This is always null

    @GraphId Long id;
    @StartNode User user;
    @EndNode Right right;

    public Privilege() {}

    public Privilege(User user, Right right) {
        this.user = user;
        this.right = right;
    }

    public void save() {
        template.save(this); // Always throws a NullPointerException
    }
}

在我的测试用例中,我可以打电话(这是有效的):

User user = userRepository.findByEmail("admin@noxgroup.co.za");
Right adminRight = rightRepository.findByName("ADMINISTRATOR");
Privilege adminPrivilege = new Privilege(user, adminRight);
template.save(adminPrivilege);

但是我更喜欢打电话(这不起作用):

User user = userRepository.findByEmail("admin@noxgroup.co.za");
User.addRight (rightRepository.findByName("ADMINISTRATOR"));

但我也无法从任何一个NodeEntities中访问模板。

2 个答案:

答案 0 :(得分:1)

您可以使用Neo4jTemplate或Neo4jOperations创建关系。

将其更改为构造函数注入。

@Autowired
public Constructor(Neo4jOperations operations) {
    this.neo4jOperations = operations;
}

通过调用存储库获得两个节点后,请执行以下操作:

Relation relation = neo4jOperations.createRelationshipBetween(user, right, Relationship.class, "RELATION_NAME", true);
neo4jOperations.save(relation);

答案 1 :(得分:1)

我的错误是我手动实例化了类,因此它不是Spring管理的。将@Component注释添加到类中并让Spring给我这个类来解决问题。

@Component // This is the line that saved the day!
@RelationshipEntity(type="HAS_RIGHT")
public class Privilege {

    @Autowired
    Neo4jOperations operations;

    @GraphId Long id;
    @StartNode User user;
    @EndNode Right right;

    public Privilege() {
        ;;
    }

    public void createRelationship(User user, Right right) {
        this.user = user;
        this.right = right;
        this.save();
    }

    /*** Getters and Setters ***/
}

然后实例化它:

...
@Autowired ApplicationContext applicationContext;
...
Privilege privilege = applicationContext.getBean(Privilege.class);
privilege.createRelationship(user, ADMINISTRATOR);