我在将包含OneToOne关系的实体保存到跟踪对象时遇到问题,该实体具有未保存的更改,但实际引用为空。
@Entity
public class Item {
... other fields
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "item"
@JoinColumn(name = "itemId", referencedColumn = "id", nullable = false)
private Set<ItemFieldData> dataSet;
}
@Entity
public class ItemFieldData {
@ManyToOne(cascade = CascadeType.ALL)
private Item item;
}
@Entity
public class TxnLog {
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "itemId")
private Item item;
}
这些是我的实体的简化版本。方案如下。
以下代码示例: -
Item item = itemRepo.findOne(itemId);
TxnLog txnLog = new TxnLog();
txnLog.setSomeFields();
ItemFieldData data = new ItemFieldData("some data");
item.addItemFieldData(data); //inserts into the Set
txnLogRepo.saveAndFlush(txnLog); //txnLog has no reference to my managed item entity yet. When stepping through the code, item in TxnLog is null.
此时抛出异常: -
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.items.ItemFieldData.field -> com.items.ItemField; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.items.ItemFieldData.field -> com.items.ItemField
所以我的问题是,为什么我的托管跟踪实体中未保存/未刷新的更改会抛出此异常,而不是正在保存和刷新的实体?
此外,在保存TxnLog时,即使它确实引用了非null的Item,我也不希望保存级联到项目。因此在TxnLog.item上没有CasecadeType。
提前致谢。