object引用未保存的瞬态实例多个关系

时间:2015-07-04 09:49:48

标签: java spring hibernate spring-mvc

我在上面的代码中发现了一些错误

HTTP Status 500 - Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: object references an unsaved transient instance - save the transient instance before flushing: crm.venkat.model.Accounts; nested exception is org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: crm.venkat.model.Accounts

@Entity
@Table(name="contacts")
public class Contact {

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinTable(name = "jt_accounts_contacts", joinColumns = {     @JoinColumn(name = "contactid") }, inverseJoinColumns = { @JoinColumn(name =     "accountid") })
    private Accounts account = new Accounts();

    //Getters and Setters
}


@Entity
@Table(name="accounts")
public class Accounts {

    @OneToMany(orphanRemoval=true, targetEntity=Contact.class,     mappedBy="account", fetch = FetchType.EAGER,  cascade=CascadeType.ALL)
    @Fetch(FetchMode.SELECT)
    private List<Contact> Contacts = new ArrayList<Contact>();

    //Getters and Setters
}

当我在填充帐户中插入联系人时,它会起作用。如果我没有填写帐户,则会出错。我希望帐户类是可选的。

1 个答案:

答案 0 :(得分:0)

这是因为您在字段初始值设定项中创建了Accounts,因此如果它没有被托管Accounts实例覆盖,Hibernate会将其视为瞬态并在刷新时抛出异常。

解决方案不是在字段初始值设定项中创建它:

@ManyToOne(fetch=FetchType.EAGER)
@JoinTable(name = "jt_accounts_contacts", joinColumns = {@JoinColumn(name = "contactid")}, inverseJoinColumns = {@JoinColumn(name = "accountid")})
private Accounts account;