Hibernate:双向一对多,一个为父对象

时间:2011-07-09 08:36:43

标签: hibernate one-to-many bidirectional

我正在尝试与“one”建立双向一对多关系作为父

我有父母:

@Entity
public class VideoOnDemand {

   @OneToMany(cascade = CascadeType.ALL)
   @LazyCollection(LazyCollectionOption.FALSE)
   @JoinColumn(name = "video_id")
   private List<CuePoint> cuePoints = new ArrayList<CuePoint>();
}

和一个孩子:

@Entity
public class CuePoint {

   @ManyToOne(cascade=CascadeType.ALL)
   @JoinColumn(name = "video_id", insertable = false, updatable = false)
   private VideoOnDemand video;
}

我使用了官方Hibernate documentation(2.2.5.3.1.1)的推荐。但是,Hibernate似乎并不理解CuePoint是一个子实体,因此,当我删除CuePoint时,它会删除VideoOnDemand以及所有其他CuePoints。

我做错了什么,正确的方法是什么?

1 个答案:

答案 0 :(得分:7)

通过这样做,您可以将唯一的双向关联映射为两个单向关联。其中一方必须标记为另一方的反面:

@Entity
public class VideoOnDemand {

   @OneToMany(mappedBy = "video", cascade = CascadeType.ALL)
   private List<CuePoint> cuePoints = new ArrayList<CuePoint>();
}

@Entity
public class CuePoint {

   @ManyToOne(cascade = CascadeType.ALL)
   @JoinColumn(name = "video_id", insertable = false, updatable = false)
   private VideoOnDemand video;
}

mappedBy属性必须包含关联另一侧的属性名称。

请注意,这确实是第2.2.5.3.1.1段所述的内容。文件。