【发布时间】: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查询更新吗?