2
我想要使用投影獲取指定條件的行數。這個想法是計算所有城市所有者的物品。使用條件和投影計算行
實體結構看起來像這樣:
@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;
}
要選擇數據I使用的下一個代碼與休眠標準:
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查詢看起來像: 休眠:從項目this_中選擇count(*)作爲y0_,其中city1_.id就像?
而且現在還不清楚,我爲什麼第一c.list()調用的效果很好,但是當我試圖用計數凸起列它不工作,並拋出未發現對象:CITY1_.ID
Hibernate的版本是4.3.4.Final
如果您只調用一次'c.list();'會發生什麼? – JamesENL 2015-03-03 01:40:09
如果我刪除了第一次調用c.list(),它會失敗,並顯示相同的錯誤 - 未找到對象:CITY1_.ID – igor 2015-03-03 06:05:12
我認爲您必須使用Projections.alias方法將該別名添加到投影中。 – JamesENL 2015-03-03 06:13:21