010. Relationships - dkkahm/study-spring-jpa GitHub Wiki

Relationship

  • OneToOne
    • A Student have a Passport
    • A Passport have a Student
  • ManyToOne, OneToMany
    • A Course have many Reviews
    • A Review have a course
  • ManyToMany
    • A Course have many Students
    • A Student have many Courses

OneToOne

  • Owning side
    @OneToOne
    private Passport passport;
  • Owned side
    @OneToOne(mappedBy = "passport")
    private Student student;

OneToMany, ManyToOne

  • Owning Side (Many)
    @ManyToOne
    private Course course;
  • Owned Side (One)
    @OneToMany(mappedBy = "course")
    private List<Review> reviews = new ArrayList<>();

ManyToMany

  • Owning side
@Entity
public class Student {
    ....

    @ManyToMany
    @JoinTable(name="STUDENT_COURSE",
            joinColumns = @JoinColumn(name="STUDENT_ID"),
            inverseJoinColumns = @JoinColumn(name="COURSE_ID")
    )
    private List<Course> courses = new ArrayList<>();
  • Owned side
@Entity
public class Course {
    ....

    @ManyToMany(mappedBy = "courses")
    private List<Student> students = new ArrayList<>();
    ....    

Saving entity with relationship

  • Set relationship to owning side and save it
    public void addReview(Long id, String rating, String description) {
        Course course = courseRepository.findById(id);

        Review review = new Review(rating, description);
        review.setCourse(course);

        reivewRepository.save(review);
   }
⚠️ **GitHub.com Fallback** ⚠️