springboot项目展示一个jpa的关联存储
时间: 2023-11-30 07:28:34 浏览: 32
好的,展示一个简单的Spring Boot项目,用于演示JPA关联存储的用法。
首先,需要在`pom.xml`文件中添加以下依赖:
```xml
<dependencies>
<!-- Spring Boot Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- H2 Database Engine -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
```
然后,创建两个实体类`Student`和`Course`,它们之间是多对多的关系。
```java
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "student_course",
joinColumns = @JoinColumn(name = "student_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "course_id", referencedColumnName = "id"))
private Set<Course> courses = new HashSet<>();
// getters and setters
}
@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
@ManyToMany(mappedBy = "courses")
private Set<Student> students = new HashSet<>();
// getters and setters
}
```
在`Student`类中,使用`@ManyToMany`注解表示与`Course`实体类之间是多对多的关系。同时,设置了级联操作`CascadeType.ALL`,表示在保存、更新或删除`Student`实体时,关联的`Course`实体也会被相应地保存、更新或删除。`@JoinTable`注解用于指定中间表的表名和列名。
在`Course`类中,使用`@ManyToMany(mappedBy = "courses")`注解表示与`Student`实体类之间是多对多的关系,并指定了关联的属性名称。
接下来,创建`StudentRepository`和`CourseRepository`两个JPA仓库类。
```java
@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}
@Repository
public interface CourseRepository extends JpaRepository<Course, Long> {
}
```
最后,创建一个简单的控制器类`CourseController`,用于测试JPA关联存储的功能。
```java
@RestController
@RequestMapping("/courses")
public class CourseController {
@Autowired
private CourseRepository courseRepository;
@Autowired
private StudentRepository studentRepository;
@PostMapping
public Course createCourse(@RequestBody Course course) {
return courseRepository.save(course);
}
@PostMapping("/{courseId}/students")
public Course addStudentToCourse(@PathVariable Long courseId, @RequestBody Student student) {
Course course = courseRepository.findById(courseId).orElseThrow(() -> new RuntimeException("Course not found"));
course.getStudents().add(student);
return courseRepository.save(course);
}
@GetMapping("/{courseId}/students")
public Set<Student> getStudentsInCourse(@PathVariable Long courseId) {
Course course = courseRepository.findById(courseId).orElseThrow(() -> new RuntimeException("Course not found"));
return course.getStudents();
}
}
```
其中,`createCourse()`方法用于创建`Course`实体;`addStudentToCourse()`方法用于将`Student`实体添加到指定的`Course`实体中;`getStudentsInCourse()`方法用于获取指定`Course`实体中的所有`Student`实体。
这样,我们就完成了一个简单的Spring Boot项目,用于演示JPA关联存储的用法。