Consider the following scenario. I have 2 table
Emp
------
EmpNo
EmpName
DeptId -- Not a foregin Key
Dept
------
DeptId
DeptName
The following are the data
Dept
-----
DeptNo DeptName
--------------------------
1 D1
2 D2
3 D3
Emp
------
EmpNo EmpName DeptId
-------------------------------------
1 John 1
2 Smith 2
3 Jon 333
4 Don 3
5 Ron 222
6 xyz 555
Emp.hbm.xml
-----------------
<hibernate-mapping>
<class name="test.Emp" table="Emp">
<id name="empNo" type="int">
<column name="empno" />
<generator class="native" />
</id>
<property name="empName" type="string">
<column name="empname" not-null="true">
</column>
</property>
<many-to-one name="dept" class="test.Dept" update="false" insert="false" not-found="ignore">
<column name="deptid"/>
</many-to-one>
</class>
</hibernate-mapping>
When the following query is executed
List<Emp> list = session.createQuery("select e from test.Emp e left join fetch e.dept where e.empNo >= 1").list();
It executes one query to reterive emp
select
emp0_.empno as empno0_0_,
dept1_.deptid as deptid1_1_,
emp0_.empname as empname0_0_,
emp0_.deptid as deptid0_0_,
dept1_.deptname as deptname1_1_
from
test.Emp emp0_
left outer join
test.Dept dept1_
on emp0_.deptid=dept1_.deptid
where
emp0_.empno>=1
Then it executes the following query 3 times unnecessarily to get the deptid (333,222,555) which is no present
select
dept0_.deptid as deptid1_0_,
dept0_.deptname as deptname1_0_
from
test.Dept dept0_
where
dept0_.deptid in (
?, ?, ?
)
select
dept0_.deptid as deptid1_0_,
dept0_.deptname as deptname1_0_
from
test.Dept dept0_
where
dept0_.deptid in (
?, ?, ?
)
select
dept0_.deptid as deptid1_0_,
dept0_.deptname as deptname1_0_
from
test.Dept dept0_
where
dept0_.deptid in (
?, ?, ?
)
Please let me know how can i stop hibernate generating extra sql which is not needed
|