Hibernate多对多映射抛出javax.persistence.EntityExistsException

时间:2016-09-15 11:52:29

标签: java hibernate spring-boot persistence

我在采访和用户之间有很多关系,所以我使用Hibernate ManyToMany映射来制作表格。出于某种原因,即使它说PK是:interview_id和user_id =>复合键,它抛出

"javax.persistence.EntityExistsException"
message
:
"A different object with the same identifier value was already associated with the session : [com.company.model.User#usr]"

这就是我的课程的样子:

Entity
@Table(name = "interview")
public class Interview {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private int id;

@Column
private String status;

@Column
private String location;

@Column(name = "applicant_id")
private int applicantId;


@Column
private Date start;

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "Interview_Emp", joinColumns = { @JoinColumn(name = "interview_id")}, inverseJoinColumns = {@JoinColumn(name = "employee_username")})
private Set<User> users = new HashSet<>(0);

//getters + setters + equals + hashcode + default constructor

对于用户:

@Entity
@Table(name = "user_t")
public class User {
@Id
@Column(name = "username")
private String username;

@Column(name = "password")
private String password;

@Column(name = "lastname")
private String lastName;

@Column(name = "firstname")
private String firstName;

@Column
private String email;

@Column(name = "phonenumber")
private String phoneNumber;

@Column
private String role;

/*
- tags are separated by | (pipe)
 */
@Column
private String tag;


//getters + setters +equals + hashcode + default constructor

当我尝试将多个用户添加到同一次访谈时,我收到了该错误。任何想法,如果我的注释有问题吗?

我试过检查我的DAO,但我只使用session.update所以我不能改变太多。这是我的Dao实施:

@Override
public void updateInterview(Interview old,Interview updated) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;
    try{
        tx = session.beginTransaction();
        Interview interviewRes = (Interview)session.get(Interview.class,old.getId());
        interviewRes.setStatus(updated.getStatus());
        interviewRes.setLocation(updated.getLocation());
        interviewRes.setStart(updated.getStart());
        interviewRes.setUsers(updated.getUsers());
        session.update(interviewRes);
        tx.commit();
    }catch (HibernateException e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace();
    }finally {
        session.close();
    }
}

0 个答案:

没有答案