使用Hibernate保存对象时收到以下错误
object references an unsaved transient instance - save the transient instance before flushing
使用Hibernate保存对象时收到以下错误
object references an unsaved transient instance - save the transient instance before flushing
当前回答
当我使用
getSession().save(object)
但当我使用
getSession().saveOrUpdate(object)
其他回答
当我使用
getSession().save(object)
但当我使用
getSession().saveOrUpdate(object)
在引入乐观锁定(@Version)之后,我对所有PUT HTTP事务都面临同样的错误
在更新实体时,必须发送该实体的id和版本。如果任何实体字段与其他实体相关,那么对于该字段,我们也应该提供id和版本值,而不是JPA首先将相关实体作为新实体持久化
示例:我们有两个实体-->Vehicle(id、Car、version);汽车(id、版本、品牌);要更新/保存车辆实体,请确保车辆实体中的“车辆”字段已提供id和版本字段
如果您的集合可以为null,请尝试:object.SetYouColaction(null);
我也面临同样的情况。通过在属性上方设置以下注释,可以解决提示的异常。
我面临的例外。
Exception in thread "main" java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.model.Car_OneToMany
为了克服,我使用了注释。
@OneToMany(cascade = {CascadeType.ALL})
@Column(name = "ListOfCarsDrivenByDriver")
private List<Car_OneToMany> listOfCarsBeingDriven = new ArrayList<Car_OneToMany>();
Hibernate抛出异常的原因:
由于我附加到父对象的子对象此时不在数据库中,因此在控制台上引发此异常。
通过提供@OneToMany(cascade={CascadeType.ALL}),它告诉Hibernate在保存父对象时将它们保存到数据库中。
如果您使用的是SpringDataJPA,那么在服务实现中添加@Transactional注释可以解决这个问题。