Hibernate 使用条件和投影计算行数

Hibernate 使用条件和投影计算行数,hibernate,count,criteria,Hibernate,Count,Criteria,我正在尝试使用投影获取指定条件的行数。这样做的目的是统计其所有者来自指定城市的所有物品 实体结构如下所示: @MappedSuperclass class BaseEntity implements Serializable { @Expose @Id @GeneratedValue(strategy = GenerationType.AUTO) Long id; } class Item extends BaseEntity{ @ManyToOne

我正在尝试使用投影获取指定条件的行数。这样做的目的是统计其所有者来自指定城市的所有物品

实体结构如下所示:

@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;
}
要选择数据,我使用下一个代码和hibernate条件:

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查询如下所示: 休眠:从该项中选择count(*)作为y0,城市1的id在哪里

我不清楚为什么第一个c.list()调用可以很好地工作,但当我尝试使用投影计算行数时,它不起作用,并抛出找不到的对象:CITY1_u1;u1.ID

Hibernate版本是4.3.4。最终解决:

hibernate似乎不支持具有多个投影关联的别名,但对于Criteria则支持。因此,我将标准别名从:

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


现在投影计数工作正常。

如果调用
c.list()仅一次?如果我删除对c.list()的第一次调用,它将失败,并出现相同的错误-找不到对象:CITY1_2;。我认为您必须使用
Projections.alias
方法将别名添加到投影中。没有领会您的想法,您能否提供一个示例?第一次调用
c.list()时可以使用sql查询进行更新是否已生成?
Criteria c = session.createCriteria(Item.class, "i");
c.createAlias("i.owner", "owner");
c.createAlias("owner.city", "city");
c.add(Restrictions.eq("city.id", 1L));