公司及其员工人数的JPA标准查询

时间:2019-05-21 02:14:42

标签: java hibernate jpa spring-data-jpa criteria-api

我正在使用JPA存储库。我有一个与雇员表一对多关系的公司表。我想获取姓氏为x的具有员工人数的公司列表。我正在尝试使用多选,但数量没有增加。这就是我想要做的。

public class CompanyEntity {
    @Id
    private UUID id;

    @Column
    private String name;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "company", orphanRemoval = true)
    private List<EmployeeEntity> employees;

    @Transient
    private Integer employeeCount;
}

...

@Autowired
private CompanyRepository repo;

...

public Page<CompanyEntity> findAllCompanies(Pageable pageable, String lastname) {

    Specification<CompanyEntity> specification = (root, criteriaQuery, criteriaBuilder) -> {
        Join employees = root.join("employees");
        criteriaQuery.groupBy(root);
        criteriaQuery.multiselect(root, criteriaBuilder.count(employees).alias("employeeCount"));

        Predicate predicate = criteriaBuilder.equal(employees.get("lastname"), lastname);
        return predicate;
    };

    Page<EmployeeEntity> page = repo.findAll(specification, pageable);

    return page;
}

2 个答案:

答案 0 :(得分:0)

计数值应该去哪里?

Specification仅配置查询的where部分。

如果您想控制包括选择列表在内的完整查询,请执行custom method implementation并直接使用EntityManager

答案 1 :(得分:0)

我最终在存储库方法上写了一个查询。

@Query("select c, count(e.id) from company c left join employee e on c.id = e.company.id where e.lastname = :lastname group by c.id")
Page<Object[]> findAll(@Param("lastname") String lastname, Pageable pageable);

此处Object[0]包含CompanyEntity,而Object[1]包含计数为Long