官方文档:https://docs.spring.io/spring-data/neo4j/docs/5.1.8.RELEASE/reference/html/#reference
因为本人服务器端neo4j版本是3,所以springboot版本就降低了。
如果你的neo4j版本是4,那么需要提高springboot版本。此外部分注解以及配置都已发生变化,你可以参考最新的springdata官方文档。
依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
application.yml:
spring:
data:
neo4j:
uri: bolt://192.168.40.128:7687
username: neo4j
password: XXXXXXXXXXXX
创建实体类:
@Data
@NodeEntity("Person")
public class Person {
@Id
@GeneratedValue
private Long id;
@Property("cid")
private int pid;
@Property
private String name;
private String character;
private double money;
private int gender;
private int age;
private String description;
@Relationship(type = "Friends",direction = Relationship.INCOMING)
private Set<Person> relationPersons;
}
创建PersonRepository
:
public interface PersonRepository extends Neo4jRepository<Person, Long> {
@Query("match(p:Person) where p.money > {0} return p")
List<Person> personList(double money);
/** 指定开始的名字 和 结束的名字 查询最短路径 限定深度为4以层包含4*/
@Query("MATCH p=shortestPath((person:Person {name:{0}})-[*1..4]- (person2:Person {name:{1}}) ) RETURN p")
List<Person> shortestPath(String startName, String endName);
}
测试:
@SpringBootTest
class BootNoe4jApplicationTests {
@Autowired
PersonRepository personRepository;
@Test
void contextLoads() {
Iterable<Person> all = personRepository.findAll();
for (Person person : all) {
System.out.println(person);
}
}
@Test
void contextLoads2() {
Iterable<Person> all = personRepository.personList(0D);
for (Person person : all) {
System.out.println(person);
}
}
@Test
void contextLoads3() {
Iterable<Person> all = personRepository.shortestPath("范闲", "叶灵儿");
for (Person person : all) {
System.out.println(person);
}
}
}