Reputation: 59950
I get an error when i use ManyToMany
relationship to persist an object, I searched a lot about this problem but I can't find the solution, someone help me to find a solution for this problem please, here is my code :
Utilisateur entity
public class Utilisateur implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(nullable = false)
private Integer id;
@Column(length = 2147483647)
private String nom;
private Integer theme;
@JoinTable(name = "utilisateur_prvilege", schema = "sch_admin", joinColumns = {
@JoinColumn(name = "privilege", referencedColumnName = "id")}, inverseJoinColumns = {
@JoinColumn(name = "utilisateur", referencedColumnName = "id")})
@ManyToMany(cascade = CascadeType.ALL)
private List<Privilege> privilegeList = new ArrayList<>();
..getters and setter..
}
Privilege entity
public class Privilege implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column
private Integer id;
private Integer pane;
@Column(length = 2147483647)
private String description;
@ManyToMany(mappedBy = "privilegeList")
private List<Utilisateur> utilisateurList = new ArrayList<>();
..getters and setter..
}
Create new Utilisateur
public void create(Utilisateur utilisateur) {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(utilisateur);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
Upvotes: 0
Views: 1242
Reputation: 873
In
@ManyToMany(mappedBy = "privilegeList")
private List<Utilisateur> utilisateurList = new ArrayList<>();
add cascadettype property and give value to persist.
Upvotes: 1
Reputation: 5877
You need to make a small change in the ManyToMany annotation.
You are defining the ManyToMany mapping in Utilisateur but your join column(not inverse mapping) is privilege
instead of utilisateur
. Make these changes and it should work now.
public class Utilisateur implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(nullable = false)
private Integer id;
@Column(length = 2147483647)
private String nom;
private Integer theme;
@JoinTable(name = "utilisateur_prvilege", schema = "sch_admin", joinColumns = {
@JoinColumn(name = "utilisateur", referencedColumnName = "id")}, inverseJoinColumns = {
@JoinColumn(name = "privilege", referencedColumnName = "id")})
@ManyToMany(cascade = CascadeType.ALL)
private List<Privilege> privilegeList = new ArrayList<>();
..getters and setter..
}
add em.flush();
line before commit and check
Many To Many mapping Tutorial link.
Upvotes: 2