正确使用RelationshipEntity

时间:2014-12-19 23:06:45

标签: java neo4j spring-data-neo4j

我正在尝试创建一个用户 - > Neo4j中的角色关系。我正在尝试利用RelationshipEntity标记来允许人们在关系中添加信息。任何人都可以帮助我,或者指出我如何建立这种关系的良好资源?

以下是代码:

USER

@NodeEntity
public class Person {

    @GraphId Long id;
    public String name;

    @RelatedToVia(type="HAS_ROLE", direction=Direction.BOTH)
    public @Fetch Set<Role> roles;


    public Person() {}
    public Person(String name) { this.name = name; }

    // Mutators below
}


ROLE

public class Role {

    @GraphId Long id;
    private RoleType roleType;

    private List<Person> users;

    private List<PrivilegeType> defaultPrivileges;


    public Role(){}

    public Role(RoleType roleType){
        this.roleType=roleType;
        this.defaultPrivileges=roleType.getDefaultPrivileges();
    }
    // Mutators below    
}


USER_ROLE_RELATIONSHIP

@RelationshipEntity(type="HAS_ROLE")
public class UserRoleRelationship {
    @GraphId Long id;

    @StartNode private Person person;

    @EndNode private Role role;

    private List<PrivilegeType> customizedPrivileges = new ArrayList<PrivilegeType>();

    // Mutators below
}

应用

@Configuration
@EnableNeo4jRepositories(basePackages = "neo4j.bakeoff.repo")
public class CopyOfApplication extends Neo4jConfiguration implements CommandLineRunner {

    public CopyOfApplication() {
        setBasePackage("neo4j.bakeoff");
    }

    @Bean
    GraphDatabaseService graphDatabaseService() {
        return new GraphDatabaseFactory().newEmbeddedDatabase("test.db");
    }

    @Autowired
    PersonRepository personRepository;

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    UserRoleRepository userRoleRepository;

    @Autowired
    GraphDatabase graphDatabase;

    public void run(String... args) throws Exception {
            // Setting up
            Person p1 = new Person("person1");
            Person p2 = new Person("person1");

            Role admin = new Role(RoleType.ADMIN);
            Role user = new Role(RoleType.USER);



            System.out.println("Before linking up with Neo4j...");
            for (Person person : new Person[]{p1, p2}) {
                System.out.println(person);
            }

            Transaction tx = graphDatabase.beginTx();
            try {
                p1 = personRepository.save(p1);
                p2 = personRepository.save(p2);

                admin= roleRepository.save(admin);
                user = roleRepository.save(user);

                UserRoleRelationship rel = new UserRoleRelationship();
                rel.setPerson(p1);
                rel.setRole(admin);
                userRoleRepository.save(rel);

                UserRoleRelationship rel2 = new UserRoleRelationship();
                rel.setPerson(p2);
                rel.setRole(user);
                userRoleRepository.save(rel2);               

                System.out.println("Lookup each person by name...");
                for (String name: new String[]{p1.name, p2.name}) {
                    System.out.println(personRepository.findByName(name));
                }

                tx.success();
            } finally {
                tx.close();
            }


    }

    public static void main(String[] args) throws Exception {
        FileUtils.deleteRecursively(new File("test.db"));

        SpringApplication.run(CopyOfApplication.class, args);
    }

}

这是我得到的堆栈跟踪

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.runCommandLineRunners(SpringApplication.java:680)
    at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:695)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
    at neo4j.bakeoff.config.Application.main(Application.java:109)
Caused by: java.lang.NullPointerException: null
    at org.springframework.data.neo4j.support.mapping.EntityStateHandler.getId(EntityStateHandler.java:81)
    at org.springframework.data.neo4j.support.mapping.EntityStateHandler.getPersistentState(EntityStateHandler.java:102)
    at org.springframework.data.neo4j.support.mapping.EntityStateHandler.getPersistentState(EntityStateHandler.java:93)
    at org.springframework.data.neo4j.support.mapping.EntityStateHandler.getOrCreateRelationship(EntityStateHandler.java:164)
    at org.springframework.data.neo4j.support.mapping.EntityStateHandler.useOrCreateState(EntityStateHandler.java:139)
    at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.write(Neo4jEntityConverterImpl.java:163)
    at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister$CachedConverter.write(Neo4jEntityPersister.java:179)
    at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:249)
    at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:231)
    at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:356)
    at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:350)
    at org.springframework.data.neo4j.repository.AbstractGraphRepository.save(AbstractGraphRepository.java:91)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:405)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:390)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:344)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy49.save(Unknown Source)
    at neo4j.bakeoff.config.Application.run(Application.java:91)
    at org.springframework.boot.SpringApplication.runCommandLineRunners(SpringApplication.java:677)
    ... 5 common frames omitted

2014-12-19 18:22:50.125  INFO 23660 --- [           main] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@234b74fd: startup date [Fri Dec 19 18:22:46 EST 2014]; root of context hierarchy
Exception in thread "main" java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.runCommandLineRunners(SpringApplication.java:680)
    at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:695)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
    at neo4j.bakeoff.config.Application.main(Application.java:109)
Caused by: java.lang.NullPointerException
    at org.springframework.data.neo4j.support.mapping.EntityStateHandler.getId(EntityStateHandler.java:81)
    at org.springframework.data.neo4j.support.mapping.EntityStateHandler.getPersistentState(EntityStateHandler.java:102)
    at org.springframework.data.neo4j.support.mapping.EntityStateHandler.getPersistentState(EntityStateHandler.java:93)
    at org.springframework.data.neo4j.support.mapping.EntityStateHandler.getOrCreateRelationship(EntityStateHandler.java:164)
    at org.springframework.data.neo4j.support.mapping.EntityStateHandler.useOrCreateState(EntityStateHandler.java:139)
    at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.write(Neo4jEntityConverterImpl.java:163)
    at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister$CachedConverter.write(Neo4jEntityPersister.java:179)
    at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:249)
    at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:231)
    at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:356)
    at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:350)
    at org.springframework.data.neo4j.repository.AbstractGraphRepository.save(AbstractGraphRepository.java:91)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:405)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:390)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:344)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy49.save(Unknown Source)
    at neo4j.bakeoff.config.Application.run(Application.java:91)
    at org.springframework.boot.SpringApplication.runCommandLineRunners(SpringApplication.java:677)
    ... 5 more

1 个答案:

答案 0 :(得分:1)

要使用@RelatedToVia,您需要有两个已连接的节点,例如用户,任务。在他们身上,您使用@RelatedToVia添加Role属性。

查看Spring文档:http://docs.spring.io/spring-data/neo4j/docs/current/reference/html/

以及完整的项目代码:https://github.com/spring-projects/spring-data-neo4j/tree/master/spring-data-neo4j-examples/cineasts