emp;//Getters//Setters} a department"/> emp;//Getters//Setters} a department">

Home  >  Article  >  Java  >  How to customize the results of a JPA query using aggregate functions?

How to customize the results of a JPA query using aggregate functions?

WBOY
WBOYforward
2023-09-18 16:49:07697browse

How to customize the results of a JPA query using aggregate functions?

Most of the time, when we use JPA queries, the results obtained are mapped to objects/specific data types. But when we use aggregate functions in queries, processing the results sometimes requires us to customize the JPA query.

Let us understand (department, employee) through an example −

Dept.java

@Entity
public class Dept {
   @Id
   private Long id;
   private String name;
   @OneToMany(mappedBy = "dep")
   private List<Employee> emp;
   //Getters
   //Setters
}

A department can have one or more employees, but an employee can only belong to one department.

Employee.java

@Entity
public class Employee {
   @Id
   private Long id;
   private Integer joiningyear;
   @ManyToOne
   private Dept dep;
   
   //Getters
   //Setters
}

Now, if we want to get the joining date and the number of employees grouped by joining date,

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
   // query methods
   @Query("SELECT e.joiningyear, COUNT(e.joiningyear) FROM Employee AS e GROUP BY e.joiningyear")
   List<Object[]> countEmployeesByJoiningYear();
}

The above query works fine, but storing values ​​in the form of List may cause errors. Instead, we can customize the JPA query to map the results of the above query into a Java class. This Java class is just a simple POJO (Plain Old Java Object) and does not need to be annotated with @Entity.

The Chinese translation of

CountEmployees.java

is:

CountEmployees.java

package com.tutorialspoint;
public class CountEmployees {
   private Integer joinyear;
   private Long totalEmp;
   
   public CountEmployees(Integer joinyear, Long totalEmp) {
      this.joinyear = joinyear;
      this.totalEmp = totalEmp;
   }
   //Getters
   //Setters
}

Now, we can customize our JPA query as shown below −

@Query("SELECT new com.tutorialspoint.CountEmployees(e.joiningyear, COUNT(e.joiningyear)) " + "FROM Employee AS e GROUP BY e.joiningyear")
List<CountEmployees> countEmployeesByJoining();

The results of the above select query will be mapped to the CountEmployees class. In this way we can customize JPA queries and map the results to java classes.

The above is the detailed content of How to customize the results of a JPA query using aggregate functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete