Question

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

Was it helpful?

Solution

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 }
    );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top