Hibernate @ManyToOne with custom generated ids

116 Views Asked by At

I have a simple question regarding @OneToMany binding with auto generated ids - relevant parts of the code are below. The issue I am facing is that the custom id being generated is not added to the sampleRequest instance in each of my deviations. It attempts to insert null in the db and I do not allow nulls, so it fails.

Thanks!

@Entity
@Table(name="SAMPLE_REQUESTS")
public class SampleRequest implements Serializable {

   @Id
   @Column(name="REQUEST_ID")
   @GenericGenerator(name="seq_id", strategy="com.tracker.services.SampleRequestSequenceGenerator")
   @GeneratedValue(generator="seq_id")
   private String requestId;

   @OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER, mappedBy = "sampleRequest") //mappedBy signals hibernate that the key for the relationship is on the other side
   private List<ProcessDeviation> deviations;

   ....
 }


@Entity
@Table(name="PROCESS_DEVIATIONS")
public class ProcessDeviation implements Serializable {

   @Id
   @GeneratedValue
   @Column(name="DEVIATION_ID")
   private int deviationId;

   @ManyToOne(cascade = CascadeType.ALL)
   @JoinColumn(name="REQUEST_ID")
   private SampleRequest sampleRequest;

   ...
}


SAMPLE_REQUESTS columns: REQUEST_ID, COMMENTS, etc.
PROCESS_DEVIATIONS columns: DEVIATION_ID, REQUEST_ID, COMMENTS, etc.
1

There are 1 best solutions below

0
On

you need to save sampleRequest first and assign its id into ProcessDeviation before saving.