0

i have 3 tables: Playlist , Advertisement , PlaylistadMap (Join Table)

1- PlayList:

@Entity
@Table(name = "playlist", catalog = "advertisedb")
public class Playlist implements java.io.Serializable {


    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private Set<PlaylistadMap> PlaylistadMaps = new HashSet<PlaylistadMap>(0);

}

2- Advertisement:

@Entity
@Table(name = "advertisement", catalog = "advertisedb")
public class Advertisement implements java.io.Serializable {


    @OneToMany(fetch = FetchType.LAZY, mappedBy = "advertisement")
    private Set<PlaylistadMap> PlaylistadMaps = new HashSet<PlaylistadMap>(0);

}

3- PlaylistadMap:

@Entity
@Table(name = "playlist_ad_map", catalog = "advertisedb")
public class PlaylistadMap implements java.io.Serializable {


    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "fk_advertisement", referencedColumnName = "pkid", nullable = false)
    private Advertisement advertisement;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "fk_playlist", referencedColumnName = "pkid", nullable = false)
    private Playlist playlist;

}

lets suppose that the playlist 1 has 3 related ads in the database:

(1,1)(1,2)(1,3) if i am trying to add 3 more ads to the old ones so the list to be updated will contain (1,1)(1,2)(1,3) (1,4)(1,5)(1,6) the records in the DB will be:

(1,1)(1,2)(1,3) (1,1)(1,2)(1,3)(1,4)(1,5)(1,6)

do i have to remove the duplicate records manually by deleting all records then insert the new ones ? or there's a solution in hibernate for this issue.

4

1 回答 1

3

您的映射是错误的:您在 Playlist 和 PlaylistadMap 之间定义了两个不同的关联,而不是一个双向关联,因为您忘记了mappedByPlayList 中的属性。

不,您不必删除现有广告并将其重新添加到集合中。它不会改变任何东西。只需将您的 3 个新广告添加到集合中,确保关联的另一端已正确初始化,一切都应该没问题。

另请注意,级联与您的问题无关。级联意味着:当我在一个实体上做 X 时,也在关联的实体上做 X。您只是在此处创建实体之间的关联。没有什么可以级联的。

于 2012-06-04T14:54:09.983 回答