使用自定义生成的ID来Hibernate @ManyToOne

时间:2014-11-17 00:22:36

标签: hibernate many-to-one

我有一个关于@OneToMany与自动生成的id绑定的简单问题 - 代码的相关部分如下。我面临的问题是,在我的每个偏差中,生成的自定义ID都不会添加到sampleRequest实例中。它试图在db中插入null,我不允许空值,因此失败。

谢谢!

@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 个答案:

答案 0 :(得分:0)

您需要首先保存sampleRequest,并在保存之前将其ID分配给ProcessDeviation。