java - TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing -
i have 2 hibernate entities coupon , couponhistory uni directional relationship between 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; ...}
there transactional service method tries saves both entities in single transaction. spring being used handle transaction here.
@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); }
i below exception when call method -
org.hibernate.transientpropertyvalueexception: object references unsaved transient instance - save transient instance beforequery flushing : com.poc.couponhistory.validitycoupon -> com.poc.coupon; nested exception java.lang.illegalstateexception: org.hibernate.transientpropertyvalueexception: object references unsaved transient instance - save transient instance beforequery flushing : com.poc.couponhistory.validitycoupon -> com.poc.coupon
i don't understand why hibernate complaining me when have saved child entity before parent entity in single transaction.
if change id generation auto coupon entity, starts working fine. want manually assign coupon code id auto generation not in scope.
any appreciated!
since not cascading coupon need managed before saving couponhistory, luckly when saving entity save() return managed persisted entity need assign coupon
@transactional public void createcoupon() { coupon coupon = new coupon(); coupon.setcode(randomstringutils.randomalphanumeric(5)); coupon.setvalidity(1); coupon = couponrepository.save(coupon);//save return managed entity couponhistory couponhistory = new couponhistory(); couponhistory.setcreatedon(new date()); couponhistory.setcoupon(coupon); couponhistoryrepository.save(couponhistory); }
Comments
Post a Comment