[JAVA] Return custom object with @Query in spring-data-jpa

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

Return custom object with @Query in spring-data-jpa
I want to return an object in CSV format with multi-line header & filter in Java
Encode query parameters with Uri Components Builder in spring
How to query Array in jsonb with Rails + postgres
In Ruby, methods with? Do not always return true/false.
Value object in 3 minutes
Mapping to a class with a value object in How to MyBatis