1. 添加依赖:
确保在项目的pom.xml文件中添加Spring Data 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=your_username
spring.data.neo4j.password=your_password
3. 定义实体类:
创建一个用于映射到Neo4j节点的实体类Person:
import org.neo4j.springframework.data.core.schema.Node;
import org.neo4j.springframework.data.core.schema.Relationship;
import org.springframework.data.annotation.Id;
import java.util.HashSet;
import java.util.Set;
@Node
public class Person {
@Id
private Long id;
private String name;
@Relationship(type = "FRIEND")
private Set<Person> friends = new HashSet<>();
// Constructors, getters, and setters
}
4. 创建Repository接口:
创建一个继承自Neo4jRepository的接口PersonRepository,用于执行与Person实体类相关的数据库操作:
import org.springframework.data.neo4j.repository.Neo4jRepository;
public interface PersonRepository extends Neo4jRepository<Person, Long> {
// Custom query methods can be defined here
}
5. 在服务类中使用Repository:
创建一个服务类PersonService,在该服务类中使用PersonRepository执行数据库操作:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PersonService {
private final PersonRepository personRepository;
@Autowired
public PersonService(PersonRepository personRepository) {
this.personRepository = personRepository;
}
public void savePerson(Person person) {
personRepository.save(person);
}
public Iterable<Person> getAllPersons() {
return personRepository.findAll();
}
public void makeFriends(Person person1, Person person2) {
person1.getFriends().add(person2);
person2.getFriends().add(person1);
personRepository.save(person1);
personRepository.save(person2);
}
}
6. 在控制器中使用服务类:
创建一个控制器类PersonController,用于处理HTTP请求:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/persons")
public class PersonController {
private final PersonService personService;
@Autowired
public PersonController(PersonService personService) {
this.personService = personService;
}
@PostMapping
public void createPerson(@RequestBody Person person) {
personService.savePerson(person);
}
@GetMapping
public Iterable<Person> getAllPersons() {
return personService.getAllPersons();
}
@PostMapping("/make-friends")
public void makeFriends(@RequestParam Long personId1, @RequestParam Long personId2) {
Person person1 = personService.getPersonById(personId1);
Person person2 = personService.getPersonById(personId2);
personService.makeFriends(person1, person2);
}
}
在这个示例中,我们定义了一个简单的社交网络数据模型,其中Person节点可以通过FRIEND关系连接。通过控制器中的HTTP端点,我们可以创建新的人物节点,获取所有人物节点,以及使两个人物成为朋友。这个示例展示了Spring Data Neo4j的基本用法,你可以根据实际需求扩展和定制。
转载请注明出处:http://www.zyzy.cn/article/detail/9318/Neo4j