简体   繁体   中英

JPA criteria query for company and its employee count

I am using JPA repositories. I have a Company table with one-to-many relationship with Employee table. I want to get list of companies with employee count who's last name is x. I am trying to use multiselect but the count is not getting populated. Here is what I am trying to do.

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;
}

Where is the count value supposed to go?

A Specification just configures the where part of a query.

If you want to control the full query including the select list do a custom method implementation and use the EntityManager directly.

I ended up writing a query on repository method.

@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);

Here Object[0] contains CompanyEntity and Object[1] contains count as Long .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM