持久性时JPA ManyToMany错误

时间:2016-08-05 20:47:51

标签: java postgresql hibernate jpa

当我使用ManyToMany关系来持久保存对象时出现错误,我搜索了很多关于这个问题但我找不到解决方案,有人帮我找到解决这个问题的方法,请点击这里是我的代码:

Utilisateur实体

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..

}

权限实体

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..

}

创建新的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();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

@ManyToMany(mappedBy = "privilegeList")
private List<Utilisateur> utilisateurList = new ArrayList<>(); 

添加cascadettype属性并赋值持久。

答案 1 :(得分:1)

您需要在ManyToMany注释中进行一些小改动。 您正在Utilisateur中定义ManyToMany映射,但您的连接列(不是逆映射)是privilege而不是utilisateur。进行这些更改,它现在应该可以正常工作。

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..

}
在提交之前

添加em.flush();行并检查

多对多映射Tutorial link