多对多关系中的空列表(不是 Table)

Empty List (not Table) at ManyToMany-Relation

我遇到了与 empty tables when using many to many relations in jpa 相同的问题。遗憾的是,这个 post 没有解决方案。我在 JPA/EclipseLink v2.6.3 中有一个具有多对多关系的 class。这里是 class 角色:

@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;
}

}

并且 class 能力

@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+"]";
}

}

当我现在使用

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);
}

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();
}

奇怪的是,当我添加或删除对象时,join-table ROLE_COMPETENCE 是正确的。当我加载 ROLE 时,他们具有可以显示的能力。但是当我从数据库加载权限时,列表 "roles" 是空的。

有什么想法吗?

我发现了我的错误。只是列表没有实例化。使用 List<Role> roles = new ArrayList<Role>(); 一切正常。