when i create a count query with hibernate - Criteria - add all the possible table from the entity class as left join which is bad performance .
The entity :
@Entity
@Table(name = "employees")
Public Class Employees {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "lz_job_stat_id")
private Integer id;
@ManyToOne
@JoinColumn(name = "departments_id")
private Departments departments;
@ManyToOne
@JoinColumn(name = "managers_id")
private Managers managers;
}
And the criteria :
public class EmployeeDao {
public List<EmpDao> findIt(){
.....
Criteria crit = createEntityCriteria().setFetchMode("departments", FetchMode.SELECT);
crit.add(Restrictions.eq("managers.deleted", false));
crit.setProjection(Projections.count("id"));
return crit.list();
}
}
And the produced SQL :
select count() as y0_
from employees this_
left outer join departments department3_
on this_.department_id=department3_.department_id
left outer join managers manager2_
on this_.manager_id=manager2_.manager_id
now when i try the crit.list - it create a left join for all the possible tables.
when its not supposed to create a join for all of them.
isnt Criteria smart enought to know i dont need this tables ? only the one i use the "WHERE CLAUSE"
is there a way to explicitly tell Criteria "DO NOT JOIN THIS TABLES !!!"
without SQL
Specify fetch type on ManyToOne
annotation:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "departments_id")
private Departments departments;
or IMHO more preferably in criteria:
criteria.setFetchMode("departments", FetchMode.SELECT)