neo4j 服务的安装及使用可参考如下博文,较为详细易用,非常不错
https://www.w3cschool.cn/neo4j/neo4j_cql_match_command.htmlhttp://w3c neo4j 语法
前言:
#写这篇文章的目的是做个简单总结,目前再做的项目中刚好用的了,只是个人的一些理解,如有不准确,还请指正,谢谢#
通过上文搭建的neo4j 服务,是一个空数据库,这个数据库有单独的cql语法,去执行一些操作,针对存储的数据,其实就是通过固定的 节点和关系 两个概念,去自定义想要的数据信息。
注意springboot 版本与neo4j版本的兼容性。
这里用的到版本分别为:
springboot 2.2.4.RELEASE
(spring-data-neo4j 5.2.4.RELEASE (neo4j-ogm-XXX:3.2.6 (neo4j-java-driver:4.0.0)))
neo4j 为 windows 版 neo4j-community-3.5.30
1、添加pom 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>
2. 配置Neo4j连接
在 application.properties
或 application.yml
中配置Neo4j连接信息:
# application.properties
spring.neo4j.uri=bolt://localhost:7687
spring.neo4j.authentication.username=neo4j
spring.neo4j.authentication.password=your_password
3. 定义实体类
使用 @Node
注解定义节点实体,@Relationship
注解定义关系。
示例:用户节点和用户关系
// User.java
@NodeEntity("User")
public class User {
@Id
@GeneratedValue
private Long id;
@Property("name")
private String name;
@Property("hasBorder")
private boolean hasBorder;
}
// Relation .java
@RelationshipEntity
public class Relation {
@Id
@GeneratedValue
private Long id;
@StartNode
private User parent;
@EndNode
private User child;
@Property("relationName")
private String relationName;
// getters/setters
}
4. 定义Repository接口
继承 Neo4jRepository
实现基本CRUD操作:
UserRepository 默认包含 save() 、delete()、findAll()、count() 等等方法,单个、批量的处理都有,同时支持自定义参数及查询语句处理数据。
save 方法包含id是即为更新操作;
public interface UserRepository extends Neo4jRepository<User, Long> {
// 自定义查询方法
User findByName(String name);
// 使用Cypher语句
@Query("MATCH (u:User)-[:HAS_ROLE]->(r:Role) WHERE u.name = $name RETURN u, collect(r)")
User findUserWithRolesByName(String name);
}
5. 编写业务逻辑
在Service层中操作节点和关系:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User createUser(String name, String roleName) {
User user = new User();
user.setName(name);
Role role = new Role();
role.setRoleName(roleName);
user.getRoles().add(role);
return userRepository.save(user);
}
public User getUserWithRoles(String name) {
return userRepository.findUserWithRolesByName(name);
}
}
6. 测试集成
使用 @DataNeo4jTest
进行切片测试:
@DataNeo4jTest
public class UserRepositoryTest {
@Autowired
private UserRepository userRepository;
@Test
public void testCreateUser() {
User user = new User();
user.setName("Alice");
userRepository.save(user);
User savedUser = userRepository.findByName("Alice");
assertThat(savedUser.getName()).isEqualTo("Alice");
}
}
7. 常见问题解决
问题1:驱动版本不兼容
-
现象:启动时报
NoSuchMethodError
。 -
解决:确保
neo4j-java-driver
版本与Neo4j服务器版本匹配:Neo4j Server Driver Version 4.x 4.4.x 5.x 5.13.x
问题2:认证失败
-
检查:确保
application.properties
中的用户名和密码正确。 -
Neo4j首次登录:默认用户为
neo4j
,首次登录需修改密码。
问题3:Cypher语法错误
-
调试:在Neo4j浏览器中(
http://localhost:7474
)直接运行查询语句验证。
8. 高级配置
自定义Neo4j驱动配置
@Configuration
public class Neo4jConfig {
@Bean
public Driver neo4jDriver(
@Value("${spring.neo4j.uri}") String uri,
@Value("${spring.neo4j.authentication.username}") String username,
@Value("${spring.neo4j.authentication.password}") String password
) {
return GraphDatabase.driver(uri, AuthTokens.basic(username, password));
}
}
启用事务管理
默认已支持事务,在Service方法上添加 @Transactional
:
@Transactional
public User updateUser(Long id, String newName) {
User user = userRepository.findById(id).orElseThrow();
user.setName(newName);
return userRepository.save(user);
}
完整的代码示例可参考 Spring Data Neo4j官方文档
-
Spring Data Neo4j 5.x:基于 Neo4j OGM,需要配置
@EnableNeo4jRepositories
。 -
Spring Data Neo4j 6+:弃用 OGM,直接使用 Java Driver,配置更简洁(通过
application.properties
)。