| Author |
Duplicate results in Hibernate many to many mapping.
|
vani venkat
Ranch Hand
Joined: Nov 21, 2006
Posts: 142
|
|
hi
i have candidatejob relation as mentioned in my earlier post
join hql query
List<Candidate> candidateUpdates = session.createQuery("from Candidate as c inner join fetch c.jobs as j").list();
this is giving duplicate records. example, i have candidate 2 applying for 2 jobs. candidateUpdates List is containing two objects of candidate and each candidate bean is populated with 2 jobs. hence when i iterate, it is giving total of 4 records. how to avoid this duplicate records ?
if i try to load just one object as below,
it is giving correct results. but the problem is when i select all the candidates and jobs. Is there anything i am missing here?
|
SCJP 1.4, SCWCD 1.5
|
 |
vani venkat
Ranch Hand
Joined: Nov 21, 2006
Posts: 142
|
|
adding distinct to the hql did the trick. sure it took lot of time.
List<Candidate> candidateUpdates = session.createQuery("select distinct c from Candidate as c inner join fetch c.jobs as j").list();
|
 |
Tim McGuire
Ranch Hand
Joined: Apr 30, 2003
Posts: 819
|
|
vani venkat wrote:adding distinct to the hql did the trick. sure it took lot of time.
you have a many to many relationship. This will return "cross joins" and distinct isn't the best way to solve it. Create an association class ( also called join table or link table )
From Java Persistence with Hibernate, chapter 7, page 298
The best way to represent this information is via an intermediate association class. In hibernate you can map the association class as an entity and map two one-to-many associations for either side.
|
 |
vani venkat
Ranch Hand
Joined: Nov 21, 2006
Posts: 142
|
|
thats nice TIm. I will try that approach today, so for mapping table there should be association class and in user and jobs, there should be one to many relation to join table. right.
I need to get that book java persistence with hibernate. is it good for beginners?
|
 |
Tim McGuire
Ranch Hand
Joined: Apr 30, 2003
Posts: 819
|
|
vani venkat wrote:
I need to get that book java persistence with hibernate. is it good for beginners?
It serves better as a reference than a beginner text. In fact, it is THE reference, but I've found it difficult to read straight through.
|
 |
 |
|
|
subject: Duplicate results in Hibernate many to many mapping.
|
|
|