条件添加实体类中的所有表,只需要它的一部分

时间:2016-06-13 07:55:58

标签: java hibernate postgresql criteria hibernate-criteria

当我使用hibernate创建计数查询时 - Criteria - 将实体类中所有可能的表添加为左连接,这是性能不佳。

实体:

@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;

}

标准:

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();
    }
}

生成的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

现在当我尝试使用crit.list时 - 它会为所有可能的表创建一个左连接。

当它不应该为所有这些创建连接时。 是不是标准聪明应该知道我不需要这张桌子?只有我使用的"WHERE CLAUSE" 有没有办法明确告诉Criteria “不要加入这个表格!!!” 没有SQL

1 个答案:

答案 0 :(得分:1)

ManyToOne注释上指定获取类型:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "departments_id")
private Departments  departments;

或恕我直言更优选的标准:

criteria.setFetchMode("departments", FetchMode.SELECT)