当前位置: 首页 > 知识库问答 >
问题:

TransientPropertyValueException:对象引用未保存的瞬态实例-在查询刷新之前保存瞬态实例

邢飞鸿
2023-03-14

我有两个hibernate实体Coupon和CouponHistory,CouponHistory和Coupon之间的单向关系。

@Entity
@Table(name = "validity_coupon")
public class Coupon {

@Id
@Column(length = 50, unique = true, nullable = false)
private String code;

private int validity;
private boolean used;

...}


@Entity
@Table(name = "coupon_history")
@TableGenerator(name = "seqGen", table = "shunya_id_gen", pkColumnName = "GEN_KEY", valueColumnName = "GEN_VALUE",
    pkColumnValue = "coupon_history_seq", allocationSize = 1)
public class CouponHistory {

@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "seqGen")
private long id;

@Temporal(TemporalType.TIMESTAMP)
private Date createdOn;

@ManyToOne(fetch = FetchType.LAZY)
private Coupon coupon;

...}

有一个事务性服务方法试图在单个事务中保存这两个实体。Spring在这里被用来处理事务。

@Transactional
public void createCoupon() {
    Coupon coupon = new Coupon();
    coupon.setCode(RandomStringUtils.randomAlphanumeric(5));
    coupon.setValidity(1);
    couponRepository.save(coupon);

    CouponHistory couponHistory = new CouponHistory();
    couponHistory.setCreatedOn(new Date());
    couponHistory.setCoupon(coupon);
    couponHistoryRepository.save(couponHistory);
}
org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : com.poc.CouponHistory.validityCoupon -> com.poc.Coupon; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : com.poc.CouponHistory.validityCoupon -> com.poc.Coupon

任何帮助都将不胜感激!

共有1个答案

季阳朔
2023-03-14

由于您不是级联优惠券,所以您需要在保存CouponHistory之前对其进行管理,幸运的是,在保存实体时,save()将返回托管的持久化实体,所以您所需要的只是将其分配给优惠券

 @Transactional
public void createCoupon() {
Coupon coupon = new Coupon();
coupon.setCode(RandomStringUtils.randomAlphanumeric(5));
coupon.setValidity(1);
coupon = couponRepository.save(coupon);//save will return the managed entity

CouponHistory couponHistory = new CouponHistory();
couponHistory.setCreatedOn(new Date());
couponHistory.setCoupon(coupon);
couponHistoryRepository.save(couponHistory);
}
 类似资料: