使用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
当前回答
在引入乐观锁定(@Version)之后,我对所有PUT HTTP事务都面临同样的错误
在更新实体时,必须发送该实体的id和版本。如果任何实体字段与其他实体相关,那么对于该字段,我们也应该提供id和版本值,而不是JPA首先将相关实体作为新实体持久化
示例:我们有两个实体-->Vehicle(id、Car、version);汽车(id、版本、品牌);要更新/保存车辆实体,请确保车辆实体中的“车辆”字段已提供id和版本字段
其他回答
另一个可能的原因是:在我的案例中,我试图在一个全新的实体上,先救孩子,再救父母。
User.java模型中的代码如下:
this.lastName = lastName;
this.isAdmin = isAdmin;
this.accountStatus = "Active";
this.setNewPassword(password);
this.timeJoin = new Date();
create();
setNewPassword()方法创建PasswordHistory记录,并将其添加到User中的历史记录集合中。由于尚未为父级执行create()语句,因此它试图保存到尚未创建的实体集合中。我所要做的就是在调用create()之后移动setNewPassword()调用。
this.lastName = lastName;
this.isAdmin = isAdmin;
this.accountStatus = "Active";
this.timeJoin = new Date();
create();
this.setNewPassword(password);
我认为这是因为您试图持久化一个对象,该对象具有对另一个尚未持久化的对象的引用,因此它尝试在“DB端”放置对不存在的行的引用
在我的例子中,当我试图使用对具有空id的实体的引用来检索相关实体时,发生了这种情况。
@Entity
public class User {
@Id
private Long id;
}
@Entity
public class Address {
@Id
private Long id;
@JoinColumn(name="user_id")
@OneToOne
private User user;
}
interface AddressRepository extends JpaRepository<Address, Long> {
Address findByUser(User user);
}
User user = new User(); // this is transient, does not have id populated
// user.setId(1L) // works fine if this is uncommented
addressRepository.findByUser(user); // throws exception
当Hibernate认为需要保存与正在保存的对象关联的对象时,在保存对象时会发生这种情况。
我遇到了这个问题,不想保存对引用对象的更改,所以我希望级联类型为NONE。
诀窍是确保设置了被引用对象中的ID和VERSION,这样Hibernate就不会认为被引用对象是需要保存的新对象。这对我有用。
查看要保存的类中的所有关系,以计算关联对象(以及关联对象的关联对象),并确保在对象树的所有对象中设置了ID和VERSION。
我也面临同样的情况。通过在属性上方设置以下注释,可以解决提示的异常。
我面临的例外。
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在保存父对象时将它们保存到数据库中。