i faced the same problem as empty tables when using many to many relations in jpa. Sadly this post was without solution. I have a class with a many-to-many relation in JPA/EclipseLink v2.6.3. Here the class ROLE:
@Entity
public class Role implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
@JoinTable(name = "ROLE_COMPETENCE", joinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "COMPETENCE_ID", referencedColumnName = "ID"))
private List<Competence> competences = new ArrayList<Competence>();
@Override
public String toString() {
return "Role [id=" + id + "]";
}
public void addCompetence(Competence competence) {
if (this.competences != null) {
if (!this.competences.contains(competence)) {
this.competences.add(competence);
competence.addRole(this);
}
}
}
public int getId() {
return id;
}
public Role() {
super();
}
public List<Competence> getCompetences() {
return competences;
}
}
And the class COMPETENCE
@Entity
public class Competence implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(length = 1024, nullable = false)
private String title;
@JsonIgnore
@ManyToMany(mappedBy = "competences", fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
private List<Role> roles;
public int getId() {
return id;
}
public Competence() {
super();
}
public void addRole(Role role) {
if (this.roles != null) {
if (!this.roles.contains(role)) {
this.roles.add(role);
role.addCompetence(this);
}
}
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Role> getRoles() {
return roles;
}
@Override
public String toString() {
return "Competence [id="+id+", title="+title+"]";
}
}
When i now use
for (int i = 0; i < 10; i++) {
Role role = new Role();
RoleService.create(role);
for (int j = 0; j < 3; j++) {
Competence c = new Competence();
c.setTitle("Competence "+i+"."+j);
CompetenceService.create(c);
lastCompetence = c;
role.addCompetence(c);
}
RoleService.update(role);
}
with
public void x(Object object) {
EntityManager em = ...
EntityTransaction tx = em.getTransaction();
tx.begin();
em.merge(object); //for x=update or em.persist(object) for x=create
tx.commit();
em.close();
}
The strange thing is that the join-table ROLE_COMPETENCE is correct when i add or remove objects. When i load ROLE's they have competences an can be shown. But the list "roles" is empty when i load competences from the database.
Any idea?