In Spring Data JPA, the aggregated result of ``` group by` `` etc. is returned as an own object that is not an entity.
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u.userId as userId, count(*) as cnt from User u group by u.userId")//It's a pointless query, but ignore it ...
List<Result> list();
@Query(value = "select user_id as userId, count(*) as cnt from users group by userId", nativeQuery = true)
List<Result> list2();
public static interface Result {
public Long getUserId();
public int getCnt();
}
}
As mentioned above, it returns the appropriate interface
to hold the result. You can use either JPQL or native query.
Recommended Posts