美文网首页
Spring Data Neo4j 使用

Spring Data Neo4j 使用

作者: shpunishment | 来源:发表于2019-06-06 18:10 被阅读0次

    添加Spring Data Neo4j相关依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-neo4j</artifactId>
    </dependency>
    <dependency>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j-ogm-http-driver</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    

    application.yml添加Neo4j环境配置

    spring:
      data:
        neo4j:
          uri: http://localhost:7474
          username: neo4j
          password: 123456
    

    Neo4j中要定义节点,使用Spring Data Neo4j的注解@NodeEntity,标记该类为节点,节点名称为 StudentNode

    @Getter
    @Setter
    @ToString
    @NodeEntity
    public class StudentNode {
        /**
         * neo4j 生成的id
         */
        @Id
        @GeneratedValue
        private Long id;
        /**
         * 属性,name
         */
        private String name;
        /**
         * 关系,定义为友谊
         */
        @Relationship(type = "FRIENDSHIP_RELATION")
        private List<FriendshipRelation> friendshipRelationList;
        /**
         * 添加友谊的关系
         * @param friendshipRelation
         */
        public void addRelation(FriendshipRelation friendshipRelation){
            if(this.friendshipRelationList == null){
                this.friendshipRelationList = new ArrayList<>();
            }
            this.friendshipRelationList.add(friendshipRelation);
        }
    }
    

    Neo4j也要定义关系,使用Spring Data Neo4j的注解@RelationshipEntity,标记其为关系,关系名为 FRIENDSHIP_RELATION,在里面定义StartNodeEndNode

    @Getter
    @Setter
    @Component
    @RelationshipEntity(type = "FRIENDSHIP_RELATION")
    public class FriendshipRelation {
        @Id
        @GeneratedValue
        private Long id;
    
        @StartNode
        private StudentNode from;
    
        @EndNode
        private StudentNode to;
    }
    

    StudentNodeRepository为数据库操作,因为后面有删除关系,所以需要@Transactional

    @Repository
    @Transactional
    public interface StudentRepository extends Neo4jRepository<StudentNode,Long> {
    
        /**
         * 通过name查找学生node
         * @param name
         * @return
         */
        StudentNode findByName(String name);
    
        /**
         * 根据name获取学生 in 友谊关系
         * @param name
         * @return
         */
        @Query("match " +
                "p=(a:StudentNode) - [r:FRIENDSHIP_RELATION*0..] -> " +
                "(b:StudentNode) " +
                "where b.name = {0} " +
                "return p")
        List<FriendshipRelation> inFriendship(String name);
    
        /**
         * 根据name获取学生 out 友谊关系
         * @param name
         * @return
         */
        @Query("match " +
                "p=(b:StudentNode) " +
                "- [rr:FRIENDSHIP_RELATION*0..] -> (c:StudentNode) " +
                "where b.name = {0} " +
                "return p")
        List<FriendshipRelation> outFriendship(String name);
    
        /**
         * 根据name获取学生 both 友谊关系
         * @param name
         * @return
         */
        @Query("match " +
                "p=(a:StudentNode) <- [r:FRIENDSHIP_RELATION*0..] -> " +
                "(b:StudentNode) " +
                "<- [rr:FRIENDSHIP_RELATION*0..] -> (c:StudentNode) " +
                "where b.name = {0} " +
                "return p")
        List<FriendshipRelation> bothFriendship(String name);
    }
    

    Neo4jServiceImpl中定义添加关系和删除关系,都需要保存from端的节点关系即可
    删除节点时使用了find和save方法,需要添加@Transactional注解

    @Service("neo4jServiceImpl")
    public class Neo4jServiceImpl implements Neo4jService {
    
        @Autowired
        private StudentRepository studentRepository;
    
        @Override
        public void saveFriendship(String fromName, String toName) {
            StudentNode from = studentRepository.findByName(fromName);
            StudentNode to = studentRepository.findByName(toName);
    
            FriendshipRelation friendshipRelation = new FriendshipRelation();
            friendshipRelation.setFrom(from);
            friendshipRelation.setTo(to);
    
            //只需要在from节点保存关系即可
            from.addRelation(friendshipRelation);
            studentRepository.save(from);
        }
    
        //删除节点时,使用find,save 需要@Transactional注解
        @Transactional(rollbackFor = Exception.class)
        @Override
        public void deleteFriendship(String fromName, String toName) {
            StudentNode fromStudentNode = studentRepository.findByName(fromName);
            List<FriendshipRelation> friendshipRelationList = fromStudentNode.getFriendshipRelationList();
            for (Iterator<FriendshipRelation> iterator = friendshipRelationList.iterator(); iterator.hasNext();) {
                FriendshipRelation relation = iterator.next();
                StudentNode fromNode = relation.getFrom();
                StudentNode toNode = relation.getTo();
    
                String fromNodeName = fromNode.getName();
                String toNodeName = toNode.getName();
                //判断 fromName 和 toName 需要删除的关系是否相等
                if(fromNodeName.equals(fromName) && toNodeName.equals(toName)){
                    iterator.remove();
                }
            }
            //只需要在from节点保存关系即可
            studentRepository.save(fromStudentNode);
        }
    }
    

    Neo4jTest进行测试,均可成功

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class Neo4jTest {
        @Autowired
        private StudentRepository studentRepository;
    
        @Autowired
        private Neo4jService neo4jService;
    
        /**
         * 保存单个节点
         */
        @Test
        public void saveStudentNode(){
            StudentNode studentNode = new StudentNode();
            studentNode.setName("张0");
            studentRepository.save(studentNode);
        }
    
        /**
         * 通过name查询学生节点
         */
        @Test
        public void findStudentNodeByName(){
            StudentNode studentNode = studentRepository.findByName("张0");
            System.out.println("");
        }
    
        /**
         * 保存批量节点
         */
        @Test
        public void saveAllStudentNode(){
            List<StudentNode> studentNodeList = new ArrayList<>();
            StudentNode studentNode;
            for(int i = 1; i <= 10; i++){
                studentNode = new StudentNode();
                studentNode.setName("张" + i);
                studentNodeList.add(studentNode);
            }
            studentRepository.saveAll(studentNodeList);
        }
    
        /**
         * 查询全部
         */
        @Test
        public void findAll(){
            //iterable to list
            List<StudentNode> studentNodeList = Lists.newArrayList(studentRepository.findAll());
            System.out.println("");
        }
    
        /**
         * 分页查询
         */
        @Test
        public void pageFindAll(){
            Pageable pageable = PageRequest.of(0,2);
            Page<StudentNode> studentNodePage = studentRepository.findAll(pageable);
            System.out.println("");
        }
    
        /**
         * 保存如下友谊关系
         *
         * 1 <-> 2 <-> 5 -> 9
         *          -> 6
         *    -> 3 <-> 7 -> 10
         *    -> 4 <-> 8
         */
        @Test
        public void saveFriendship(){
            neo4jService.saveFriendship("张1","张2");
            neo4jService.saveFriendship("张1","张3");
            neo4jService.saveFriendship("张1","张4");
    
            neo4jService.saveFriendship("张2","张1");
            neo4jService.saveFriendship("张2","张5");
            neo4jService.saveFriendship("张2","张6");
    
            neo4jService.saveFriendship("张3","张7");
    
            neo4jService.saveFriendship("张4","张8");
    
            neo4jService.saveFriendship("张5","张2");
            neo4jService.saveFriendship("张5","张9");
    
            neo4jService.saveFriendship("张7","张3");
            neo4jService.saveFriendship("张7","张10");
    
            neo4jService.saveFriendship("张8","张4");
        }
    
        /**
         * 根据name查询 both 友谊关系
         */
        @Test
        public void getBothFriendship(){
            List<FriendshipRelation> friendshipRelationList1 = studentRepository.bothFriendship("张1");
        }
    
        /**
         * 根据name查询 in 友谊关系
         */
        @Test
        public void getInFriendship(){
            List<FriendshipRelation> friendshipRelationList1 = studentRepository.inFriendship("张1");
        }
    
        /**
         * 根据name查询 out 友谊关系
         */
        @Test
        public void getOutFriendship(){
            List<FriendshipRelation> friendshipRelationList1 = studentRepository.outFriendship("张1");
        }
    
        /**
         * 删除 1 -> 3 友谊关系
         */
        @Test
        public void deleteFriendship(){
            neo4jService.deleteFriendship("张1","张3");
        }
    }
    
    保存单节点 张0
    保存多节点 张1~张10
    保存 张1~张10 友谊关系
    删除 张1 和 张3 关系

    相关文章

      网友评论

          本文标题:Spring Data Neo4j 使用

          本文链接:https://www.haomeiwen.com/subject/xjiuxctx.html