I have a database schema where I have to map many to many relationship
***** Tables **********
person
--------
id - int
name - varchar
color
-------------
id - int
color - varchar
person_color
------------
person_id - int (matches an id from person)
color_id - int (matches an id from color)
I have Converted the above scenario to JPA @Entities as
@Entity
public class Person {
@Id
@GeneratedValue
private Integer id;
private String name;
@ManyToMany(cascade = {CascadeType.ALL})
private List<Color> colors;
/// setters getters are there
}
and
@Entity
public class Color {
@Id
@GeneratedValue
private Integer id;
private String color;
@ManyToMany(cascade = {CascadeType.ALL})
private List<Person> person;
/// setters getters are there
}
the above code creates four tables
person
person_color
color
color_person
but I wanna only three tables as
person
person_color
color
what is wrong with the above code and wanna example of saving data to database any resource or link to good example of saving data using JPA many to many relation.
Update your Person class to following
@Entity
public class Person {
@Id
@GeneratedValue
private Integer id;
private String name;
@ManyToMany(targetEntity = Color.class, cascade = {CascadeType.ALL})
@JoinTable(name = "person_color", joinColumns = { @JoinColumn(name = "person_id") },
inverseJoinColumns = { @JoinColumn(name = "color_id") })
private List<Color> colors;
/// setters getters are there
}
Update your Color class to following
@Entity
public class Color {
@Id
@GeneratedValue
private Integer id;
private String color;
@ManyToMany(mappedBy = "colors", cascade = CascadeType.ALL)
private List<Person> persons;
/// setters getters are there
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With