使用子对象保存主对象时使用休眠保存时出错

时间:2014-10-15 19:45:56

标签: java spring hibernate

我创建了实体bean作为公司与User有@ManyToOne的关系。我们怎样才能实现使用hibernate。

@Entity
@Table(name="company_details")
public class Company implements Serializable {
    private Long id;
    private String nameOfCompany;
    private User createdBy;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="Id", nullable=false)
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }

    @Column(name="NAME_OF_COMPANY", nullable=false)
    public String getNameOfCompany() {
        return nameOfCompany;
    }
    public void setNameOfCompany(String nameOfCompany) {
        this.nameOfCompany = nameOfCompany;
    }
    @ManyToOne(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
    @JoinColumn(name="USER_ID")
    public User getUsers() {
        return users;
    }
    public void setUsers(User users) {
        this.users = users;
    }

}

当我保存公司对象时,hibernate会抛出异常:

  

org.hibernate.NonUniqueObjectException:与...不同的对象   相同的标识符值已与会话关联:   [com.myProject.models.User#23]

保存代码如下:

Company company = new Company();
company.setNameOfCompany("my comp");
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
com.myProject.models.User userDetails = userProfileService.getUserInfoByUserName(user.getUsername());
customer.setUsers(userDetails);
Long id = companyService.save(company);

DAO:

public Long save(Company comp) throws Exception {
         sessionFactory.getCurrentSession().save(comp);
        return comp.getId();
    }

我已经通过了Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session帖子,但它对我来说没用。

1 个答案:

答案 0 :(得分:0)

在您的情况下,您将分配@ManyToOne映射并仅传递单个对象。

因此,使用

更改Model映射
@ManyToOne(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
@JoinColumn(name="USER_ID")
List<User> users;

    public List<User> getUsers() {
        return users;
    }
    public void setUsers(List<User> users) {
        this.users = users;
    }

现在,当您保存公司实体时,请将用户列表传递给setUsers方法