JPA - Aggregate Function
Aggregate functions return resultant values by calculating result based on input values. For example, Max() function returns the maximum of passed column value.
Following the same example employee management used in previous chapters, we will go through the service classes using aggregate functions of JPQL.
Example - Usage of Max() Aggregate Function using JPA
Create a class named AggregateFunction.java under com.tutorialspoint.eclipselink.service package as follows−
Aggregate.java
package com.tutorialspoint.eclipselink.service;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;
public class AggregateFunction {
public static void main( String[ ] args ) {
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
EntityManager entitymanager = emfactory.createEntityManager();
//Aggregate function
Query query1 = entitymanager.createQuery("Select MAX(e.salary) from Employee e");
Double result = (Double) query1.getSingleResult();
System.out.println("Max Employee Salary: " + result);
}
}
Output
Run the code as Java Application in Eclipse IDE.
After compilation and execution of the above program you will get following result on the console panel of eclipse IDE.
Max Employee Salary: 40000.0
Advertisements