Search code examples
existsquerydsl

QueryDSL 4 select + where + exists


Just started using queryDSL at my job. So far I think the syntax is very intuitive.

I need to convert a very simple SQL query to queryDSL, but I don't know what do do with the EXISTS clause.

SELECT * FROM XRDocument document
 WHERE status = 0
   AND EXISTS
     (
       select * FROM XEntity X WHERE X.pid in (11,22,33)
     )
  AND NOT EXISTS
     (
      select * FROM XEntity X WHERE X.pid in (44,55,66)
     )

I have all my Q classes ready. So far this is all I have (pseudo code):

JPAQuery query = new JPAQuery(em);
query.from(xDocument).where(xDocument.status.eq(0))

I read the documentation but there's no ".exists()" method. I also tried using the JDOExpressions class but I couldn't come up with a solution.

Can anybody point me to the right direction?


Solution

  • You could do something like

    JPAQuery query = new JPAQuery(em)
        .select(xDocument)
        .from(xDocument)
        .where(xDocument.status.eq(0)
            .and(JPAExpressions.selectOne()
                .from(xEntity)
                .where(xEntity.pid.in(11,22,33)
                .exists())
            .and(JPAExpressions.selectOne()
                .from(xEntity)
                .where(xEntity.pid.in(44,55,66)
                .notExists()));