Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Duplicate results in Hibernate many to many mapping.

 
vani venkat
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
vani venkat
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 820
IntelliJ IDE Tomcat Server VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 820
IntelliJ IDE Tomcat Server VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic