1.安装jdk,这个就不讲了,版本为1.8
2.安装neo4j
官网:https://neo4j.com/download-center/
区分为社区版和企业版(收费)区别如下:
注意:4.X版本需要对应java11以上,所以我们选择3.5
下载完毕后解压,进入conf目录,修改配置文件
"dbms.default_listen_address=0.0.0.0"取消注释
然后进入bin目录,运行./neo4j start
启动后访问:7474/browser/">http://
举些简单例子:
查询老李的所有相关属性: MATCH (n)-[r*1..]->(m) where n.name='老李' return n,r,m
查询所有张三的同事关系: match (n)-[r:`同事`]-(m) where n.name='张三' return m,n,r;
查询老李的所有同事的相关属性: match(n)-[r:`同事`]-(q)-[b]-(m) where n.name='老李' return n,m,r,b,q
引入neo4j依赖:
org.springframework.boot spring-boot-starter-data-neo4j2.5.8 org.neo4j neo4j-ogm-http-driver3.2.1
编写实体类
package com.zjlab.leqing.entity;
import lombok.Data;
import org.springframework.data.neo4j.core.schema.GeneratedValue;
import org.springframework.data.neo4j.core.schema.Id;
import org.springframework.data.neo4j.core.schema.Node;
import org.springframework.data.neo4j.core.schema.Relationship;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@Node
@Data
public class Person {
@Id
@GeneratedValue
private Long id;
private String name;
private String sex;
private Person() {
// Empty constructor required as of Neo4j API 2.0.5
}
public Person(String name) {
this.name = name;
}
@Relationship(type = "房产")
public Set houses;
@Relationship(type = "车")
public Set cars;
@Relationship(type = "同事")
public Set associates;
public void haveHouse(House house) {
if (houses == null) {
houses = new HashSet<>();
}
houses.add(house);
}
public void haveCar(Car car) {
if (cars == null) {
cars = new HashSet<>();
}
cars.add(car);
}
public void workWith(Person person) {
if (associates == null) {
associates = new HashSet<>();
}
associates.add(person);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(id, person.id) && Objects.equals(name, person.name) && Objects.equals(sex, person.sex) && Objects.equals(houses, person.houses) && Objects.equals(cars, person.cars) && Objects.equals(associates, person.associates);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
编写mapper:
package com.zjlab.leqing.mapper; import com.zjlab.leqing.entity.Person; import org.springframework.data.neo4j.repository.Neo4jRepository; import org.springframework.data.neo4j.repository.query.Query; import java.util.List; public interface PersonRepository extends Neo4jRepository{ List findByNameIsLike(String name); @Query("match (n:House)<-[r:`房产`]-(m:Person) where n.address contains {address} return m,n,r;") Person findByHouseAddress(String address); @Query("MATCH (n)-[r*1..]->(m) where n.name contains {name} return n,r,m") List findAllByName(String name); }
启动类增加注解:
编写controller:
最终结果:



