通过级联插入oneToMany会在添加多个子项时导致错误,NonUniqueObjectException

时间:2015-08-18 17:18:04

标签: hibernate

Project正在使用Spring 4.0.0.RELEASE,Hibernate 4.3.1 Final 如果只添加一个子对象,它可以正常工作。它引发了2个或更多的错误。 请让我知道我做错了什么。感谢。

//child
@Entity
@Table(name = "MEMBER_ROLE")
public class Role implements Serializable {

    @Id
    @Column(name = "ROLE_ID")
    private int roleId;

    @Column(name = "ROLE")
    private String role;

    @ManyToOne
    @JoinColumn(name = "MEMBER_ID")
    private Member member;

    //getters setters
    //...
    //...
}
//DAO
@Repository
@Transactional
public class DaoImpl implements Dao {

    @Autowired
    SessionFactory sessionFactory;

    public void saveOrUpdate(Member m) {

        Member member = new Member();
        member.setUsername(m.getUsername());
        member.setPassword(m.getPassword());

        /*
         * It works with one object Role
         */
        List<Role> roleList = new ArrayList<>();
        roleList.add(new Role("ROLE_USER", member));
        roleList.add(new Role("ROLE_ADMIN", member));

        member.setRoleList(roleList);
        sessionFactory.getCurrentSession().saveOrUpdate(member);
    }
}
org.hibernate.NonUniqueObjectException: 
A different object with the same identifier value was already associated with the session : [com.project.model.Role#0]

错误:

#announcement{
  position: relative;
  bottom: 0px;
  left: 0px;
  width: 50%;
  margin-left: 10px;
}

1 个答案:

答案 0 :(得分:0)

是不是因为你忘了告诉Hibernate自动生成roleId的值?

这里缺少@GeneratedValue:

@Id
@Column(name = "ROLE_ID")
private int roleId;