An HQL query is generating extra joins because two tables are added to the from clause twice.
Hibernate version: 3
Mapping documents:
schema:
Code:
Table - Timesheet
id (pk)
name
Table - Entry
id (pk)
date
Join Table - Timesheet_Entry
timesheet_id
entry_id
mapping:
Timesheet.hbm.xml:
...
Code:
<id name="id" type="long">
<column name="ID" />
<generator class="native" />
</id>
<set name="timesheetEntries" table="TIMESHEET_ENTRY"
cascade="all,delete-orphan" fetch="subselect" >
<key column="TIMESHEET_ID" not-null="true" />
<many-to-many column="ENTRY_ID"
class="Entry" lazy="false" unique="true" />
</set>
...
Code between sessionFactory.openSession() and session.close():HQL:
Code:
.createQuery("select sum(t.timesheetEntries.hours) as hours " +
"from Timesheet t where t.id=? and " +
"t.timesheetEntries.entryDate=?");
Name and version of the database you are using: MySQL 5.0.18
The generated SQL (show_sql=true):TIMESHEET_ENTRY and ENTRY are in the from clause twice causing the sum to not be accurate.
(with sensible table aliases):
Code:
select sum(e1.HOURS) as hours
from timesheet t1, TIMESHEET_ENTRY te1,
entry e1, TIMESHEET_ENTRY te2, entry e2
where t1.ID=te2.TIMESHEET_ID
and te2.ENTRY_ID=e2.ID
and t1.ID=te1.TIMESHEET_ID
and te1.ENTRY_ID=e1.ID
and t1.ID=1
and e2.ENTRY_DATE='2006-02-06'