springboot整合neo4j

本文介绍如何使用SpringBoot整合Neo4j图数据库,通过示例代码展示节点和关系的管理,解决多标签节点查询难题,实现灵活的图谱构建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目需求使用java对neo4j图谱进行管理。自己使用springboot整合neo4j,并实现节点和关系管理的demo。

需求说明: 节点有entity,content,param等类型,但是要求所有节点必须有node类型,也就是说有两个labels属性。

pom.xml

<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.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>

application.yml

spring:
  data:
    neo4j:
      uri: http://127.0.0.1:7474
      username: neo4j
      password: pactera

使用@labels注解实现

@labels注解在spring-data-neo4j文档上找到的(https://docs.spring.io/spring-data/data-neo4j/docs/current/reference/html/)。这样做可以在创建节点时添加任意lables。

@NodeEntity(label="entity")
@Data
public class EntityNode  {
	public EntityNode() {
		List<String> labels = new ArrayList<>();
		labels.add("node");
		labels.add("entity");
		this.setLabels(labels);
	}	

	@GeneratedValue
	@Id
	private Long id;
    
	@Labels
    private List<String> labels ;
	
	public String nodeId;
	
	public String nodeName;

	private String[] concepts;
	
	private String regex;
	// 关系映射
	@Property(name="default")
	private String defaultJump;
}
// 继承Neo4jRepository 
public interface EntityRepository extends Neo4jRepository<EntityNode, Long> {

	EntityNode findByNodeId(@Param("nodeId") String NodeId);
}

这样做易于理解和实现,但是却存在很多问题:因为@NodeEntity中label="entity",所以EntityRepository 中实现的函数全部都是针对entity类型的节点的。比如nodeRepository.findAll()函数对应执行语句为:"statement":"MATCH (n:`entity`) RETURN n"。那么如果给你一个id,你不知道具体类型,那么这时该使用entityRepository,contentRepository还是paramRepository来findById呢?

使用继承

@NodeEntity注解源码

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface NodeEntity {

    String LABEL = "label";

    String label() default "";
}

当时我也被这个问题困惑很久,最后发现@NodeEntity注解上有@Inherited注解,想到是否可以使用继承?

父类node,定义节点的公共属性。(自己代码中父类没有使用@Data,而是写的get,set方法)

@NodeEntity(label="node")
@Data
public class Node implements Serializable{
	
	private static final long serialVersionUID = 942659633583923942L;

	@GeneratedValue
	@Id
	private Long id;
	
	public String nodeId;
	
	public String nodeName;
	
}

public interface NodeRepository  extends Neo4jRepository<Node, Long>  {

}

子类,具体类的具体属性

@NodeEntity(label="entity")
@Data
@EqualsAndHashCode(callSuper=false)
public class EntityNode extends Node {

	private static final long serialVersionUID = -3441407202518609463L;
	
	private String[] concepts;
	
	private String regex;
	
	@Property(name="default")
	private String defaultJump;
}


public interface EntityRepository extends Neo4jRepository<EntityNode, Long> {

	EntityNode findByNodeId(@Param("nodeId") String NodeId);
}

使用EntityRepository 创建entity类型节点

    @Test
	@Rollback(false)
	public void createNode() {
		EntityNode entityNode= new EntityNode();
		entityNode.setNodeId("test001");
		entityNode.setNodeName("测试1");
		entityNode.setRegex("123123123131");
		entityRepository.save(entityNode);
	}
// 执行语句
{"statement":"UNWIND {rows} as row CREATE (n:`entity`:`node`) SET n=row.props RETURN row.nodeRef as ref, ID(n) as id, {type} as type

使用nodeRepository删除任意类型的节点

    @Test
	@Rollback(false)
	public  void deleteById() {
		nodeRepository.deleteById(1488l);
	}
// 执行语句
{"statement":"MATCH (n:`node`) WHERE ID(n) = { id } WITH n RETURN n"}
{"statement":"MATCH (n) WHERE ID(n) = { id } OPIONAL MATCH (n)-[r0]-() DELETE r0, n"}

 

### Spring Boot 整合 Neo4j 示例教程 #### 三、添加Neo4j依赖 为了使Spring Boot项目能够与Neo4j图数据库交互,需在项目的`pom.xml`文件中加入必要的依赖项。这些依赖不仅包含了Neo4jJava驱动程序,还集成了Spring Data Neo4j所提供的简化接口,从而让开发人员能更加便捷地执行CRUD操作和其他高级功能[^1]。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-neo4j</artifactId> </dependency> ``` #### 四、配置Neo4j连接信息 接着,在`application.properties`或`application.yml`文件内指定Neo4j服务器的具体地址、端口号、用户名及密码等参数,以便应用程序建立到目标数据库的有效链接[^4]。 对于`.properties`格式: ```properties spring.data.neo4j.uri=bolt://localhost:7687 spring.data.neo4j.username=neo4j spring.data.neo4j.password=password ``` 而对于`.yml`格式,则如下所示: ```yaml spring: data: neo4j: uri: bolt://localhost:7687 username: neo4j password: password ``` #### 五、创建实体类 基于领域模型设计原则定义相应的实体对象,并利用注解方式映射至Neo4j中的节点(Node)或关系(Relationship),这有助于提高代码可读性和维护性的同时也增强了系统的灵活性和扩展能力[^3]。 例如,下面是一个简单的用户实体示例: ```java import org.neo4j.ogm.annotation.GeneratedValue; import org.neo4j.ogm.annotation.Id; import org.neo4j.ogm.annotation.NodeEntity; @NodeEntity public class User { @Id @GeneratedValue private Long id; private String name; public User() {} public User(String name) { this.name = name; } // getters and setters... } ``` #### 六、编写Repository接口 借助Spring Data JPA风格的仓库模式来封装针对特定类型的持久化逻辑,只需声明继承自`CrudRepository<T,ID>`或其他更具体的泛型接口即可获得一系列常用方法的支持,无需手动编码SQL语句就能完成增删改查等功能[^2]。 ```java import org.springframework.data.repository.CrudRepository; public interface UserRepository extends CrudRepository<User, Long> { } ``` #### 七、测试验证 最后一步就是通过单元测试或者其他形式检验整个流程是否正常工作,比如向Neo4j实例插入新记录并查询返回预期的结果集合等等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值