1.添加依赖:首先,在你的 Spring Boot 项目中的 pom.xml
文件中添加 Neo4j 相关的依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>
2.配置数据源:在 application.properties
(或 application.yml
)文件中配置 Neo4j 数据库的连接信息。
spring.data.neo4j.uri=bolt://localhost:7687
spring.data.neo4j.username=neo4j
spring.data.neo4j.password=your_password
3.创建实体类:在你的 Spring Boot 项目中创建实体类来映射到 Neo4j 中的节点和关系。
import org.springframework.data.neo4j.core.schema.Id;
import org.springframework.data.neo4j.core.schema.Node;
@Node
public class Person {
@Id
private Long id;
private String name;
// Getters(获取器)和 Setters(设置器)
}
4.创建 Repository:创建一个 Neo4j 的 Repository 接口来处理对数据库的 CRUD 操作。
import org.springframework.data.neo4j.repository.Neo4jRepository;
public interface PersonRepository extends Neo4jRepository<Person, Long> {
// 自定义查询方法可以在这里定义
}
5.使用 Repository:在你的业务逻辑中使用自动生成的 Repository 接口来操作数据库。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PersonService {
@Autowired
private PersonRepository personRepository;
public void savePerson(Person person) {
personRepository.save(person);
}
public Iterable<Person> getAllPersons() {
return personRepository.findAll();
}
// 其他业务逻辑方法
}
6.运行项目:完成以上步骤后,运行你的 Spring Boot 项目,并确保 Neo4j 数据库处于运行状态。你的项目就可以通过 Repository 接口来访问和操作 Neo4j 数据库了。