标准,需要只选择根字段

时间:2014-05-26 10:36:24

标签: java hibernate hibernate-criteria

我遇到了Hibernate标准的问题。我需要通过一些动态条件以及Empoyee字段(LAZY字段)的条件获取公司列表。我创建了这样的Criteria:

Criteria criteria = session.createCriteria(Company.class);

criteria.createAlias("employee", "employee");
criteria.add(Restrictions.eq("employee.someFieldForWhere", "text"));

criteria.list();

对于Employee字段的添加条件,我必须添加别名(在我的情况下,我添加了具有相同名称的别名' employee')。

但在这种情况下,我得到了错误的非法SQL查询 - 在这种情况下,Hibernate尝试从别名中选择所有字段:

    select
        this_.id as id1_0_1_,
        this_.employee_id as employee2_0_1_,
        employee1_.id as id1_1_0_,
        employee1_.someBigField as someBigF2_1_0_,
        employee1_.someFieldForWhere as someFiel3_1_0_ 
    from
        Company this_ 
    inner join
        Employee employee1_ 
            on this_.employee_id=employee1_.id 
    where
        employee1_.someFieldForWhere=?

这不是不可接受的,因为表Employee包含许多文件,我不需要在我的请求中加载它(在我的例子中它加载id,someFieldForWhere和someBigField)。

所以问题 - 如何在子实体上创建带有条件的条件,而没有这个子实体的选择字段?

我需要这样的东西:

        select
            this_.id as id1_0_1_,
            this_.employee_id as employee2_0_1_,
        from
            Company this_ 
        inner join
            Employee employee1_ 
                on this_.employee_id=employee1_.id 
        where
            employee1_.someFieldForWhere=?

游戏项目,完整来源 - https://github.com/Akvel/criteriaTest

1 个答案:

答案 0 :(得分:0)

您可以通过在条件

上设置投影来指定要选择的字段
    Criteria criteria = session.createCriteria(Company.class);

    criteria.createAlias("employee", "employee");
    criteria.add(Restrictions.eq("employee.someFieldForWhere", "text"));

    ProjectionList projections = Projections.projectionList();
    // just the root id
    projections.add(Projections.id());
    // the associated entity id
    projections.add(Projections.property("employee.id");

    criteria.setProjections(projections);

    criteria.list();

请参阅Hibernate docs