title: TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing
body: <p>I have two hibernate entities Coupon and CouponHistory with Uni Directional Relationship between CouponHistory and Coupon.</p>
  
  <pre><code>@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;
  
  ...}
  </code></pre>
  
  <p>There is a Transactional Service Method that tries to saves both the entities in a Single Transaction. Spring is being used to handle transaction here.</p>
  
  <pre><code>@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);
  }
  </code></pre>
  
  <p>I get the below exception when i call this method -</p>
  
  <pre><code>org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : com.poc.CouponHistory.validityCoupon -&gt; 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 -&gt; com.poc.Coupon
  </code></pre>
  
  <p>I don't understand why hibernate is complaining me when i have saved the child entity before parent entity in single transaction.</p>
  
  <p>If i change id generation to Auto for Coupon Entity, then everything starts working fine. But i want to manually assign the Coupon Code so Id auto generation is not in scope.</p>
  
  <p>Any help would be appreciated!</p>