Mahmoud Saleh
Mahmoud Saleh

Reputation: 33625

@OneToMany save duplicate records

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.

Upvotes: 1

Views: 2265

Answers (1)

JB Nizet
JB Nizet

Reputation: 692121

Your mapping is wrong: you defined two different associations between Playlist and PlaylistadMap instead of a single bidirectional one, because you forgot the mappedBy attribute in PlayList.

And no, you don't have to remove and re-add the existing ads to the set. It wouldn't change anything. Just add your 3 new ads to the set, make sure the other side of the association is initialized correctly, and everything should be fine.

Also note that cascading is not related to your problem. Cascading means: when I do X on an entity, also do X on the associated entities. You're just creating an association between entities here. There's nothing to cascade.

Upvotes: 4

Related Questions