Issue
I have two tables student and categories. Student and category has ManyToMnay relationship.
@Entity
@Getter
@Setter
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "student_id",nullable = false)
private Integer id;
@Column(name = "student_name")
private String name;
@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name = "student_has_subject",
joinColumns = @JoinColumn(name = "student_student_id"),
inverseJoinColumns = @JoinColumn(name = "student_subject_id"))
private List<Subject> subjects = new ArrayList<>()
}
Subject.class
@Entity
@Getter
@Setter
@Table(name = "subject")
public class Subject {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "subject_id", nullable = false)
private Integer id;
@Column(name = "subject_name",nullable = false)
private String name;
@ManyToMany(mappedBy = "subjects")
private List<Student> students = new ArrayList<>();
}
But when I execute this in IDE. student_has_subject Table created but without creating primary key.
mysql> describe workflow_services;
+-------------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------+------+-----+---------+-------+
| student_id | bigint(20) | NO | PRI | NULL | |
| subject_id | bigint(20) | NO | PRI | NULL | |
+-------------+------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
How could I make both forieng key as primary.
When I create this no primary key created.
How to create new table name student_has_subject with all column as primary key
Solution
Preferred way to map a ManyToMany is using a Set rather than a List - ManytoMany.
Also using a Set will generate a PK in the join tableAnswered By - johnnyutts
Answer Checked By - Mary Flores (JavaFixing Volunteer)