in JPA, Spring

JPA – Associations @OneToOne , @OneToMany, @ManyToOne, @ManyToMany part 3

Previously I wrote about OneToMany and ManyToOne and OneToOne associations, in this post I will show you how to handle ManyToMany associations.

Example that I will be using is classical example of many to many association where we have a teacher that can can teach  many students and a student that can be thought by multiple teachers. To do this I have created two entities Teacher and Student :


When many to many association is created we will have three tables STUDENT and TEACHER and TEACHER_STUDENT. Last one binds two tables together with two foreign keys STUDENT_FK_ and TEACHER_FK_ pointing to their primary keys.

Observe how to setup owning side of the association with @JoinTable you can specify table name and with two @JoinColumn one for owning and inverse side. Both JoinColumn specify names for foreign keys.


Unit Test

To make sure all works tests should always be created

It is important to note that both sides must be updated in order to make all work properly. Here are those two lines.

This covers all JPA associations types.



Write a Comment