Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

many to many mapping and saving issue using Spring Data JPA

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.


1 Answers

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
}
like image 151
Balwinder Singh Avatar answered Feb 04 '26 16:02

Balwinder Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!