I have a many to many relation in my class but the problem is that the table created by spring boot contains and id which is not a primary key.
My code looks like:
@JoinTable(name = "T_Commande_Produit",
joinColumns = @JoinColumn(name = "idCommande"),
inverseJoinColumns = @JoinColumn(name = "idProduit"))
private List<Produit> products;
And the table created looks like this
+-------------+--------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------+------+-----+---------+-------+
| id | bigint | NO | MUL | NULL | |
| id_commande | bigint | NO | MUL | NULL | |
| id_produit | bigint | NO | MUL | NULL | |
+-------------+--------+------+-----+---------+-------+
If you are creating ManyToMany relation then you don't need a third ID variable you can simply set the primary key as id_commande and id_produit combination and you don't need a third entity in this case.
But if you still want to manually create a table that includes three fields that is the id, id_commande, and id_produit then you can create an Entity class That contains OneToMany Relation with others.
Code Example:
The third Entity is a table referencing both the Produit and Commande.
@Entity
class ThirdEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne
@JoinColumn(name = "id_commande")
private Commande commande;
@ManyToOne
@JoinColumn(name = "id_produit")
private Produit produit;
}
Produit Entity
@Entity
class ProduitEntity {
// constructors and other fields excluded for simplicity.
@OneToMany(mappedBy = "produit") // here produit is a object name of Produit in ThirdEntity
private List<ThirdEntity> list;
}
Commande Entity
@Entity
class CommandeEntity {
// constructors and other fields excluded for simplicity
@OneToMany(mappedBy = "commande") // here commande is a object name of Produit in ThirdEntity
private List<ThirdEntity> list;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.