【问题标题】:Count rows using criteria and projection使用标准和投影计算行数
【发布时间】:2015-05-03 10:05:25
【问题描述】:

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

实体结构如下所示:

@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: select count(*) as y0_ from item this_ where city1_.id like ?

我不清楚为什么第一个 c.list() 调用效果很好,但是当我尝试使用投影计算行数时它不起作用并抛出 object not found: CITY1_.ID

Hibernate 版本是 4.3.4.Final

【问题讨论】:

  • 如果您只调用一次c.list(); 会发生什么?
  • 如果我删除 c.list() 的第一次调用,它会失败并出现同样的错误 - 找不到对象:CITY1_.ID
  • 我认为您必须使用Projections.alias 方法将别名添加到投影中。
  • 没听懂你的意思,能否举个例子?
  • 第一次调用c.list();时可以用sql查询更新吗?

标签: hibernate count criteria


【解决方案1】:

已解决: 看起来hibernate不支持Projections的多个关联的别名,但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));

现在投影计数效果很好。

【讨论】:

    猜你喜欢
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多