使用条件和投影计算行数

时间:2015-03-02 21:57:46

标签: hibernate count criteria

我尝试使用投影获取指定条件的行数。我们的想法是计算其所有者来自指定城市的所有项目。

实体结构如下所示:

@MappedSuperclass
class BaseEntity implements Serializable {
    @Expose
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;
}

class Item extends BaseEntity{
    @ManyToOne
    @JoinColumn(name = 'owner_id')
    Owner owner;
}

class Owner extends BaseExntity{
    @ManyToOne
    @JoinColumn(name = "city_id")
    City city;
}

class City extends BaseExntity{
    @Column(name = "name")
    String name;
}

要选择数据我使用下一个具有休眠标准的代码:

Criteria c = session.createCriteria(Item.class);

//just select all instances that have cityId = 1
c.createAlias("owner.city", "city");
c.add(Restrictions.like("city.id", 1L));
c.list(); //1st invocation, this works well

//Trying to count instances that have cityId = 1
ProjectionList properties = Projections.projectionList();
properties.add(Projections.rowCount(), "count");

c.setProjection(properties);
c.list(); //2nd invocation, here I receive an exception - object not found: CITY1_.ID 

在第二个c.list()调用sql查询看起来像: Hibernate:从item_中选择count(*)作为y0_,其中city1_.id喜欢?

我不清楚为什么第一次c.list()调用效果很好但是当我尝试使用投影计算行时它不起作用并抛出对象而不是发现:CITY1_.ID

Hibernate版本是4.3.4.Final

1 个答案:

答案 0 :(得分:1)

<强>解决: 看起来hibernate不支持具有多个预测关联的别名,但对于Criteria来说。因此,我改变了标准别名:

Criteria c = session.createCriteria(Item.class);
c.createAlias("owner.city", "city");
c.add(Restrictions.like("city.id", 1L));

为:

Criteria c = session.createCriteria(Item.class, "i");
c.createAlias("i.owner", "owner");
c.createAlias("owner.city", "city");
c.add(Restrictions.eq("city.id", 1L));

现在投影计数效果很好。