Home > Software engineering >  Spring JPA count where group by
Spring JPA count where group by

Time:01-06

I want to transform a sql query in JPA.

SELECT status, count(*)
FROM abc
WHERE type='XXX'
GROUP BY status

I need something in a JPARepository with sql.

@Repository
public interface ABCRepository extends JpaRepository<abc, Long> {

   long countByStatusAndType(final A type, final B status);
}

Is it Possible?

CodePudding user response:

Firstly, create class containing parameters status and count for handling results, then create method in repository with query

@Query("SELECT status, count(*) as count FROM abc WHERE type=:type GROUP BY status")
List<CustomResultClass> countByStatus(String type);

CodePudding user response:

In JPA, with status and type you can simply define a method using Query annotation.

@Query("SELECT count(*) FROM abc WHERE type=:type GROUP BY status =:status")
long countByStatusAndType(String type, String status);

For custom response, if you want to add fields refer: How to return a custom object from a Spring Data JPA GROUP BY query

  •  Tags:  
  • Related