我正在尝试使用Hibernate条件api执行子查询但是却无法完全弄清楚如何去做。假设有2个表,SHOPS和EMPLOYEES,其中SHOPS拥有所有商店信息,而EMPLOYEES是所有商店中所有雇员的大表(没有设置外键)。我正在尝试编写一个查询,该查询从SHOPS表中检索商店ID和地址,然后通过联接检索商店中的雇员数量并计算EMPLOYEES表。像这样:
SELECT a.SHOP_ID, a.SHOP_ADDRESS, (SELECT COUNT(*) FROM
SHOP_EMPLOYEES b WHERE b.SHOP_ID = a.SHOP_ID) as NUM_EMPLOYEES FROM <--Problem here
SHOPS a
WHERE
QUERY_STATUS ='Open'
所以我有一个Java类商店,包括shopId,shopAddres,numEmployees和Employees的类似商品。
我的子查询:
DetachedCriteria subquery = DetachedCriteria.forClass(
Employee.class, "b").add(
Property.forName("b.shopId").eqProperty("a.shopId"))
.setProjection(
Projections.projectionList().add(
Projections.rowCount()));
主要标准查询:
List shopListRet = session.createCriteria(Shop.class, "a")
.setProjection(
Projections.projectionList().add(
Projections.property("a.shopId"))).add(Subquery..."DONT KNOW WHAT SHOULD COME HERE").list();
我的问题是:
由于 -J
答案 0 :(得分:4)
使用SQL投影添加子查询。
String subSql = "SELECT COUNT(*) FROM SHOP_EMPLOYEES b WHERE b.SHOP_ID = a.SHOP_ID"
...
.add( Projections.sqlProjection(
subSql ,
new String[] { "NUM_EMPLOYEES" },
new Type[] { Hibernate.LONG }
);