Neo4j之Springboot-data-neo4j 5.2.6開發整理

Neo4j之Springboot-data-neo4j 5.2.6開發遇到的問題

1、依賴導入

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-neo4j</artifactId>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

2、application.yml配置

server:
  port: 80
spring:
  mvc:
    static-path-pattern: /**
  resources:
    static-locations: classpath:/static/, classpath:/templates/
  data:
    neo4j:
      uri: bolt://localhost:7687
      username: neo4j
      password: neo4j
    main:
    allow-bean-definition-overriding: true

3、Neo4jconfig配置文件

//參考官網:https://docs.spring.io/spring-data/neo4j/docs/5.2.6.RELEASE/reference/html/#reference.ogm-support

@Configuration
@EnableNeo4jRepositories(basePackages = "com.liu.ex.repository")
@EntityScan(basePackages = "com.liu.ex.domain")
@EnableTransactionManagement
public class Neo4jConfig {

    @Bean
    public org.neo4j.ogm.config.Configuration configuration() {
        org.neo4j.ogm.config.Configuration configuration = new org.neo4j.ogm.config.Configuration.Builder()
                .uri("bolt://localhost:7687")
                .credentials("neo4j", "neo4j")
                .build();
        return configuration;
    }

    @Bean
    public SessionFactory sessionFactory() {
        // with domain entity base package(s)
        return new SessionFactory(configuration(), "com.liu.ex.entity");
    }

    @Bean
    public Neo4jTransactionManager transactionManager() {
        return new Neo4jTransactionManager(sessionFactory());
    }
}

4、編寫實體類

//節點實體

import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Property;

@NodeEntity
public class PersonNode {

    @Id
    @GeneratedValue
    private Long id;

    @Property(name = "name")
    private String name;

    public PersonNode() {
    }

    public PersonNode(Long id, String name) {
        this.id = id;
        this.name = name;
    }

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

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "PersonNode{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

//關係實體
@RelationshipEntity(type = "PersonRelation")
public class PersonRelation {

    @Id
    @GeneratedValue
    private Long id;

    @StartNode
    private PersonNode startNode;

    @EndNode
    private PersonNode endNode;

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public PersonNode getStartNode() {
        return startNode;
    }

    public void setStartNode(PersonNode startNode) {
        this.startNode = startNode;
    }

    public PersonNode getEndNode() {
        return endNode;
    }

    public void setEndNode(PersonNode endNode) {
        this.endNode = endNode;
    }

    @Override
    public String toString() {
        return "PersonRelation{" +
                "id=" + id +
                ", startNode=" + startNode +
                ", endNode=" + endNode +
                ", name='" + name + '\'' +
                '}';
    }
}

5、DAO(repository)層

/**
* springboot-data 支持將常用的方法名自動解析成neo4j查詢語句
* 因此有些方法不需要寫註解、數據庫操作語句
* 也可以自定義操作數據庫的語句
*/
@Repository
public interface PersonRepository extends Neo4jRepository<PersonNode, Long>, CrudRepository<PersonNode, Long> {

    //通過名字查詢節點
    PersonNode findByName(@Param("name") String name);
//    PersonNode findByName(String name);

    //查詢所有節點
    List<PersonNode> findAll();

    //模糊查詢,$0表示第一個參數
    @Query("match (n:PersonNode) where n.name =~ $0 return n")
    List<PersonNode> findByNameLike(@Param("likes") String likes);

}

//模糊查詢需要在service層進行字符串拼接
//例如 likes =  ".*" + likes +".*";

//關係
@Repository
public interface PersonRelationRepository extends Neo4jRepository<PersonRelation, Long>, CrudRepository<PersonRelation,Long> {

    @Query("match p=(n:PersonNode)-[r]-(m:PersonNode) where r.name = $0  return p")
    List<PersonRelation> findPersonRelationByRelationName(@Param("RelationName") String RelationName);

    @Query("MATCH p=()-[r:PersonRelation]->() RETURN p")
    List<PersonRelation> findAllPersonRelation();

    @Override
    Iterable<PersonRelation> findAll();
}

6、service接口

public interface PersonService {

    PersonNode findByName(@Param("name") String name);

    List<PersonNode> findAll();

    List<PersonNode> findByNameLike(@Param("likes") String likes);
    
}

//關係
public interface PersonRelationService {
    List<PersonRelation> findPersonRelationByRelationName(String RelationName);

    List<PersonRelation> findAllPersonRelation();

    Iterable<PersonRelation> findAll();
}

7、serviceimpl實現類

//service接口
@Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonRepository personRepository;

    @Autowired
    private PersonService personService;

    public PersonNode findByName(String name) {
        return personRepository.findByName(name);
    }

    @Override
    public List<PersonNode> findAll() {
        return personRepository.findAll();
    }

    @Override
    public List<PersonNode> findByNameLike(String likes) {
        //爲了實現模糊查詢
        likes =  ".*" + likes +".*";
        System.out.println(likes);
        return personRepository.findByNameLike(likes);
    }
}

//關係
@Service
public class PersonRelationServiceImpl implements PersonRelationService {

    @Autowired
    private PersonRelationRepository relationRepository;
    @Override
    public List<PersonRelation> findPersonRelationByRelationName(String RelationName) {
        return relationRepository.findPersonRelationByRelationName(RelationName);
    }

    @Override
    public List<PersonRelation> findAllPersonRelation() {
        return relationRepository.findAllPersonRelation();
    }

    @Override
    public Iterable<PersonRelation> findAll() {
        return relationRepository.findAll();
    }
}

8、測試類

import com.liu.ex.entity.PersonNode;
import com.liu.ex.repository.PersonRepository;
import com.liu.ex.service.PersonService;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@WebAppConfiguration
@ComponentScan("com.liu.ex")
class Neo4jexApplicationTests {

    @Autowired
    private WebApplicationContext wac;
    @Autowired
    private MockMvc mockMvc;

    //模擬controller層
    @Before
    public void setUp (){
//        mockMvc = MockMvcBuilders.standaloneSetup(new helloController()).build();
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();//建議使用這種
    }

    //模擬controller層
    @Test
    public void testController() throws Exception {
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/findone").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();

        String content=mvcResult.getResponse().getContentAsString();    //得到返回結果
        System.out.println(content);
    }

    @Autowired
    private PersonRepository personRepository;
    private final static Logger log = LoggerFactory.getLogger(Neo4jexApplicationTests.class);

    @Test
    void contextLoads() {
        personRepository.deleteAll();

        PersonNode personNode = new PersonNode("大頭");
        PersonNode personNode1 = new PersonNode("小頭");

        List<PersonNode> team = Arrays.asList(personNode, personNode1);

        personRepository.save(personNode);
        personRepository.save(personNode1);
        
        log.info(personRepository.findByName("大頭").toString());
    }

    @Resource
    private PersonService personService;

    @Test
    public void testPerson(){
        PersonNode nodes = personService.findByName("大頭");
        List<PersonNode> list = personService.findAll();
//        System.out.println(list);
//        System.out.println(nodes);
        //模糊查詢
        List<PersonNode> nodeList = personService.findByNameLike("頭");
        System.out.println(nodeList);
    }
}

//關係
@Autowired
    private PersonRelationService relationService;

    @Test
    public void testRelation(){
        List<PersonRelation> relations = relationService.findPersonRelationByRelationName("朋友");
       Iterable<PersonRelation> relation = relationService.findAll();
        List<PersonRelation> relationList = relationService.findAllPersonRelation();
        System.out.println(relation);
        System.out.println(relations);
        System.out.println(relationList);
    }

9、controller層

@RestController
@RequestMapping("/")
public class personController {

    @Autowired
    private PersonService personService;

    @RequestMapping("/findone")
    public PersonNode findByName(String name){
    	//此處name我用 “大頭”代替
        PersonNode personNode = personService.findByName("大頭");
        System.out.println(personNode);
        return personNode;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章