Hibernate: bi-directional one-to-many with one as parent

耗尽温柔 提交于 2019-12-05 00:16:38

问题


I'm trying to setup a bi-directional one-to-many relationship with "one" as parent

I have a parent:

@Entity
public class VideoOnDemand {

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

and a child:

@Entity
public class CuePoint {

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

I used recommendations from the official Hibernate documentation (2.2.5.3.1.1). However, Hibernate doesn't seem to understand that CuePoint is a child entity, so, when I delete the CuePoint, it deletes VideoOnDemand as well with all the other CuePoints.

What am I doing wrong and what is the right way?


回答1:


By doing that, you'be mapped a unique bidirectional association as two unidirectional associations. One of the side must be marked as the inverse of the other:

@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;
}

The mappedBy attribute must contain the name of the attribute of the other side of the association.

Note that this is indeed what is described at paragraph 2.2.5.3.1.1. of the documentation.



来源:https://stackoverflow.com/questions/6633708/hibernate-bi-directional-one-to-many-with-one-as-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!