目的
本案例以简单农业知识图谱作为案例,讲解了springboot如何操作neo4j数据库,仅供初学者参考。
技术
springboot,neo4j,spring-data-neo4j 6.3.0
注:spring-data-neo4j 5.x的版本和6.x的版本节点实体定义、关系定义、操作等差别较大,需要注意。
快速开始
在前面文章《以农业知识图谱为案例介绍neo4j图数据库的使用》和《知识图谱构建利器:图数据库Neo4j的环境部署和简单使用》中已经详细介绍了neo4j数据库的安装运行和数据库本身一些简单的创建、查询、删除等操作,下面直接分享如何使用springboot操作neo4j。
农业图谱关系:不同农作物生长于不同的环境:农作物->地域环境
1.创建springboot项目
使用IntelliJ IDEA,Eclipse或其它方式创建springboot项目,具体不再赘述,请自行创建项目。
2.添加neo4j依赖
打开对应项目的pom.xml文件,增加以下内容并重新加载。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>
注:因为Spring-Data-Neo4j属于SpringData项目,因此填写依赖的时候不需要填写版本号,会根据SpringBoot版本自动设置。
3.添加neo4j数据库配置信息
打开application.properties文件,按照如下内容填写。
application.properties
spring.neo4j.uri=bolt://localhost:7687
spring.neo4j.authentication.username=neo4j
spring.neo4j.authentication.password=wp123321
4.创建neo4j图数据库节点对应的实体类
Node注解,声明这是一个节点类;里面内容为标签;@Data 为 lombok工具包的注解。
@Id 和 @GeneratedValue 声明这是一个自动生成的id,类型为Long
@Property指明该字段为节点的属性
@Relationship注解,声明该字段是与本节点有关的关系列表,type参数为该关系的名称; direction参数为该关系的方向(对应neo4j箭头的方向),离开本节点(OUTGOING,默认)或进入本节点(INCOMING)。
@TargetNode注解,简单理解为箭头的朝向
农作物节点实体:
@Node("Crops")
@Data
public class Crops {
@Id
@GeneratedValue
private Long id;
@Property
private String name;
@Relationship(type = "Grown_IN", direction = Relationship.Direction.OUTGOING)
private List<GrownIn> locations;
@Relationship(type = "Location", direction = Relationship.Direction.OUTGOING)
private Location location;
}
地域位置节点实体:
@Node("Location")
@Data
public class Location {
@Id
@GeneratedValue
private Long id;
@Property
private String region;
@Property
private String Qihou;
}
关系实体
@RelationshipProperties
@Data
@Builder
public class GrownIn {
@Id
@GeneratedValue
private Long id;
@TargetNode
private final Location location;
}
5.创建Repository
Crops节点和Location节点对应的Repository,只需要继承Neo4jRepository即可。
@Repository
public interface CropsRepository extends Neo4jRepository<Crops,Long> {
}
@Repository
public interface LocationRepository extends Neo4jRepository<Location,Long> {
}
6.创建单元测试
创建节点
@Test
void createNode(){
Location location = new Location();
location.setRegion("成都");
location.setQihou("湿热");
locationRepository.save(location);
}
查询节点
@Test
void queryNode(){
Location location = locationRepository.findById(10L).get();//通过ID查询节点
System.out.println("================================"+location.getRegion());
List<Location> locationList = locationRepository.findAll();//查询所有节点
}
创建关系
@Test
void createRelative(){
Crops crops = cropsRepository.findById(11L).get();//通过ID查询农作物节点
Location location = locationRepository.findById(8L).get();//通过ID查询地域位置节点
crops.getLocations().add(GrownIn.builder().location(location).build());//创建映射关系
cropsRepository.save(crops);//保存
}