如何在Query DSL中编写Union All查询

时间:2017-06-19 21:19:10

标签: querydsl

需要实现sql查询,如:

SELECT A.class, A.section 
FROM 
STUDENT A 
INNER JOIN DEPARTMENT on A.student_id = B.id 
WHERE DEPT_NBR is not null
UNION ALL
SELECT A.class, A.section 
FROM 
TEACHER A 
INNER JOIN DEPARTMENT on A.teacher_id = B.id 
WHERE DEPT_NBR is not null

如何使用QueryDSL编写此类语句? (我没有使用任何JPA)。任何帮助/提示都非常感谢!

2 个答案:

答案 0 :(得分:1)

有很多例子可以帮到你。

public void union_multiple_columns() throws SQLException {
        SubQueryExpression<Tuple> sq1 = query().from(employee).select(employee.firstname, employee.lastname);
        SubQueryExpression<Tuple> sq2 = query().from(employee).select(employee.lastname, employee.firstname);
        List<Tuple> list = query().union(sq1, sq2).fetch();
        assertFalse(list.isEmpty());
        for (Tuple row : list) {
            assertNotNull(row.get(0, Object.class));
            assertNotNull(row.get(1, Object.class));
        }
    }

此示例取自项目本身: https://github.com/querydsl/querydsl/blob/8f96f416270d0353f90a6551547906f3c217833a/querydsl-sql/src/test/java/com/querydsl/sql/UnionBase.java#L73

答案 1 :(得分:0)

,以便其他人不会搜索太多... JPA doesn't support unions,因此在JPA之上运行时querydsl不支持联合。当在原始SQL上运行时,它确实支持它们,请参阅natros的答案。