Search code examples
hibernatecriteriahibernate-criteria

Hibernate : Repetition in FetchMode.JOIN


I have a dept table and an emp table. The dept table had a one-to-many relation with emp table w.r.t the deptId.

When i tried this code:

session.createCriteria(Dept.class).setFetchMode("empMap", FetchMode.JOIN)
       .list();

This is the generated output in my console for the sql query generated by the hibernate:

select this_.DEPT_ID as DEPT1_1_1_, this_.DEPT_NAME as DEPT2_1_1_, 
empmap2_.DEPT_ID as DEPT3_3_, empmap2_.EMP_ID as EMP1_3_, 
empmap2_.EMP_ID as formula0_3_, empmap2_.EMP_ID as EMP1_0_0_, 
empmap2_.EMP_NAME as EMP2_0_0_, empmap2_.DEPT_ID as DEPT3_0_0_, 
empmap2_.AGE as AGE0_0_, empmap2_.SEX as SEX0_0_ 
from dept this_, emp empmap2_ 
where this_.DEPT_ID=empmap2_.DEPT_ID(+)

In the generated hibernate query I can clearly see that there are repetition in columns of the emp table. But i don't want these repetitions to appear. How to avoid the repetition in the hibernate generated query then?

Please inform how to remove these repetitions.

Regards,


Solution

  • There are a few workarounds to this:

    1. You can add your items to a HashSet or LinkedHashSet - which will remove the duplicates or
    2. You can try using a different fetch mode. See this link for details on the fetch modes here - I've had pretty good results using SUBSELECT.