Search code examples
querydsl

How to do unions from different tables in QueryDSL


my question is simple how can I select from different tables using SQL QueryDSL for example

SELECT cat.name as name, cat.voice as voice , cat.purr FROM cat UNION
SELECT dog.name as name, dog.voice as voice , NULL as voice FROM dog;

Solution

  • Something like this should work

    QCat cat = QCat.cat;
    QDog dog = QDog.dog;
    
    StringPath name = Expressions.stringPath("name");
    StringPath voice = Expressions.stringPath("voice");
    StringPath purr = Expressions.stringPath("purr");
    
    SQLQueryFactory queryFactory = new SQLQueryFactory(MySQLTemplates.DEFAULT, null);
    SQLQuery<Tuple> cats =
        SQLExpressions.select(cat.nome.as(name), cat.voice.as(voice), cat.purr.as(purr)).from(cat);
    SQLQuery<Tuple> dogs =
        SQLExpressions.select(
                dog.nome.as(name),
                dog.voice.as(voice),
                Expressions.as(Expressions.nullExpression(), purr))
            .from(dog);
    queryFactory.select(name, voice, purr).from(SQLExpressions.union(cats, dogs)).fetch();