Reputation: 7852
I have two java hibernate entities:
@Entity
public class Match_soccer extends Match{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int mid;
...
And other one:
@Entity
public class Algo {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@OneToMany
private List<Match_soccer> matches = new ArrayList<Match_soccer>();
...
And if I try save two different Algo
entities but with some matches
list I get Duplicate entry '6028' for key 'UK_auyvi1qkpdtaqrpuyv9je5rda'
exception.
Hibernate create in database 3 tables: Algo
Match_soccer
and Table:
Algo_Match_soccer
with columns:
Algo1_id int(11)
matches_mid int(11) PK
My goal is to assign list of matches to Algo. Matches can be some in 2 different Algo objects.
Algo a1 = new Algo();
Algo a2 = new Algo();
SoccerDAO sd = new SoccerDAO();
List<Match_soccer> ms = sd.getMatches(DateFrom,DateTo); // Matches from database
a1.setMatches(ms);
a2.setMatches(ms);
I use this function to insert:
public void insertAlgo(Algo1 a){
try {
session.beginTransaction();
session.save(a);
session.getTransaction().commit();
}
catch (RuntimeException e) {
session.getTransaction().rollback();
session.clear();
throw e;
}
Upvotes: 2
Views: 267
Reputation: 1533
Due to Match_soccer
could have relationships with many Algo
entities instance, the matches
association/collection must be`@ManyToMany.
If you leave the association as @OneToMany it will define the UK//PK constraint for match_id
that doesn't allows you to set same matches to two different Algo
instances
Upvotes: 1
Reputation: 692131
Matches can be some in 2 different Algo objects
Then you don't have a OneToMany association, but a ManyToMany association. since an Algo has several matches, and a match belongs to several algos.
Change your mapping, and change the database schema accordingly: the PK of the join table should be the pair of IDs, and not just the match ID.
Upvotes: 1