@manytomany

Showing posts with label @manytomany. Show all posts
Showing posts with label @manytomany. Show all posts

The best way to map @ManyToMany


@ManyToMany

Many to many relationships can be easily mapped by creating another table using @JoinTable as follows.

Student entity

@Data
@Table(name = "Student")
@Entity
public class Student implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String studentName;

    @ManyToMany
    @JoinTable(
        name = "student_task",
        joinColumns = @JoinColumn(name = "task_id"),
        inverseJoinColumns = @JoinColumn(name = "student_id")
    )
    private Set<Task> tasks = new HashSet<>();
}


Task entity

@Entity
@Data
@Table(name = "tasks")
public class Task implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String taskName;

    @ManyToMany(mappedBy = "tasks")
    private Set<Student> students = new HashSet<>();
}