UNION to JPA Query

前端 未结 7 939
日久生厌
日久生厌 2020-12-01 15:57

Is it possible to query \"UNION\" in JPA and even \"Criteria Builder\"?

I\'m looking for examples, but so far i got no result.

Does anyone have any examples

7条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 16:12

    There is no direct union for JPA, what I did was to build two specifications.

    Specification specification = Specification.where(null);
    Specification specification2 = Specification.where(null;
    

    They belong to a single table but return different values

    specification = specification.and((root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.equal(criteriaBuilder.function(MONTH, Integer.class, root.get("deliveryExpirationDate")), month));
            specification2 = specification2.and((root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.lessThan(criteriaBuilder.function(MONTH, Integer.class, root.get("deliveryExpirationDate")), month))
                .and((root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.equal(root.get("enable"), true));
    

    for this example it is a table of tasks that in the first specification I need the tasks of the current month enabled and disabled, and in the second specification I only need the tasks enabled of the previous months.

    Specification specificationFullJoin = Specification.where(specification).or(specification2);
    

    Esto es muy útil para que la lista de tareas devueltas tenga paginación.

    taskRepository.findAll(specificationFullJoin, pageable).map(TaskResponse::new); //Here you can continue adding filters, sort or search.
    

    It helps me a lot, I hope it is what they are looking for or that it serves them something.

提交回复
热议问题