Hibernate criteria query

早过忘川 提交于 2019-12-12 17:39:02

问题


I am trying to execute a subquery using Hibernate criteria api but not been able to figure out completely how to go about it. Assuming there are 2 tables, SHOPS and EMPLOYEES, where SHOPS has all the shops information and EMPLOYEES is a big table of all the employess in all the shops (No foreign keys set). I am trying to write a query, which retrieves the shop id and address from the SHOPS table and then retrieves the number of employess in a shop by a join and count on EMPLOYEES table. Something like this:

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'

So I have a Java class Shop with shopId, shopAddres, numEmployees and similar for Employees.

My subquery:

DetachedCriteria subquery = DetachedCriteria.forClass(
  Employee.class, "b").add(
  Property.forName("b.shopId").eqProperty("a.shopId"))
  .setProjection(
    Projections.projectionList().add(
      Projections.rowCount()));

And a main criteria query on the lines of:

List shopListRet = session.createCriteria(Shop.class, "a")
  .setProjection(
    Projections.projectionList().add(
      Projections.property("a.shopId"))).add(Subquery..."DONT KNOW WHAT SHOULD COME HERE").list();

My question is:

  • How do i associate the Detached query as a subquery to collect the count result in a class variable numEmployees in Shop class?

Thanks -J


回答1:


Use a SQL projection to add the subquery.

  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 }
    );


来源:https://stackoverflow.com/questions/4682683/hibernate-criteria-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!