我有一个hibernate映射的数据结构,当我尝试删除它时会出错。
@Entity
@Table(name = "TYPE")
public class Type {
@Id
private int id;
private String name;
}
@Entity
@Table(name = "BOOKS")
public class Book {
@Id
private int id;
@ManyToOne(fetch = FetchType.EAGER, optional = false)
private Type type;
}
当我尝试删除Book对象时,我得到了
Caused by: org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value: com....Book.type; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value: com...Book.type
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:645)
at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:424)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.delete(HibernateTemplate.java:846)
at org.springframework.orm.hibernate3.HibernateTemplate.delete(HibernateTemplate.java:842)
当我删除optional = false参数时,我看到Hibernate从TYPES表中删除了对象。如果有来自oposite端的ManyToOne链接,为什么它会尝试删除类型实体? 感谢。
UPD: 父对象中提供书籍集合。要删除它,我使用以下代码:
Information info = getInformationById(id);
if (info != null) {
getHibernateTemplate().delete(info);
}
upd2(完整层次结构):
@Entity
@Table(name = "INFO")
public class Information {
@Id
@Column(name = "ID")
private int id;
@Version
private int version;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "INFO_ID")
private Set<Details> details;
... }
@Entity
@Table(name = "DETAILS")
public class Details {
@Id
private int id;
@Version
private int version;
@Column(name = "INFO_ID")
private int infoId;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "DETAILS_ID", nullable = false)
private Set<Books> books = new HashSet<Book>();
... }
Chain is:Info-&gt; Details-&gt; Books。每本书都有一种类型,很可能是很多书都有相同的类型。我删除信息对象时,我不想删除类型实体。