ManyToMany-Relation的空列表(不是表)

时间:2016-07-26 11:44:01

标签: java jpa eclipselink

我面临与empty tables when using many to many relations in jpa相同的问题。可悲的是,这篇文章没有解决方案。我在JPA / EclipseLink v2.6.3中有一个具有多对多关系的类。这里有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;
}

}

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

}

我现在使用

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

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

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

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

相关问题