Close

Spring Data JPA - Derived Count Query

[Last Updated: Aug 21, 2018]

Spring Data JPA also support count query derived methods. Instead of using 'find', we need to start our query method with 'count' keyword. For example:

public interface EmployeeRepository extends CrudRepository<Employee, Long> {
    long countByDept(String deptName);
}

Calling above method:

  long count = repo.countByDept("IT");

Example

Entity

@Entity
public class Employee {
    private @Id
    @GeneratedValue
    Long id;
    private String name;
    private String dept;
    private int salary;
    .............
}

Repository

public interface EmployeeRepository extends CrudRepository<Employee, Long> {
    long countByDept(String deptName);
    long countBySalaryGreaterThanEqual(int salary);
    long countByNameEndingWith(String endString);
    long countByNameLike(String likeString);
}

Example Client

@Component
public class ExampleClient {

    @Autowired
    private EmployeeRepository repo;

    public void run() {
        List<Employee> employees = createEmployees();
        repo.saveAll(employees);

        System.out.println(" -- finding all employees --");
        Iterable<Employee> all = repo.findAll();
        all.forEach(System.out::println);

        System.out.println(" -- finding the employee count in IT dept --");
        long count = repo.countByDept("IT");
        System.out.println(count);

        System.out.println(" -- finding the employee count with salary greater or equal to 4000  --");
        count = repo.countBySalaryGreaterThanEqual(4000);
        System.out.println(count);

        System.out.println(" -- finding the employee count with name ending with 'e'  --");
        count = repo.countByNameEndingWith("e");
        System.out.println(count);

        System.out.println(" -- finding the employee count with name like '%a_a' --");
        count = repo.countByNameLike("%a_a");
        System.out.println(count);
    }

    private List<Employee> createEmployees() {
        return Arrays.asList(
                Employee.create("Diana", "Admin", 3000),
                Employee.create("Mike", "IT", 1000),
                Employee.create("Rose", "IT", 4000),
                Employee.create("Sara", "Admin", 3500),
                Employee.create("Tanaka", "IT", 3000),
                Employee.create("Charlie", "IT", 4500)
        );
    }
}

Main class

public class ExampleMain {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(AppConfig.class);
        ExampleClient exampleClient = context.getBean(ExampleClient.class);
        exampleClient.run();
        EntityManagerFactory emf = context.getBean(EntityManagerFactory.class);
        emf.close();
    }
}
 -- finding all employees --
Employee{id=1, name='Diana', dept='Admin', salary=3000}
Employee{id=2, name='Mike', dept='IT', salary=1000}
Employee{id=3, name='Rose', dept='IT', salary=4000}
Employee{id=4, name='Sara', dept='Admin', salary=3500}
Employee{id=5, name='Tanaka', dept='IT', salary=3000}
Employee{id=6, name='Charlie', dept='IT', salary=4500}
-- finding the employee count in IT dept --
4
-- finding the employee count with salary greater or equal to 4000 --
2
-- finding the employee count with name ending with 'e' --
3
-- finding the employee count with name like '%a_a' --
3

Example Project

Dependencies and Technologies Used:

  • spring-data-jpa 2.0.9.RELEASE: Spring Data module for JPA repositories.
    Uses org.springframework:spring-context version 5.0.8.RELEASE
  • hibernate-core 5.3.5.Final: Hibernate's core ORM functionality.
    Implements javax.persistence:javax.persistence-api version 2.2
  • h2 1.4.197: H2 Database Engine.
  • JDK 1.8
  • Maven 3.5.4

Derived Count Query Methods Example Select All Download
  • spring-data-jpa-derived-count-query
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • EmployeeRepository.java
          • resources
            • META-INF

    See Also