LoginSignup
6
4

More than 5 years have passed since last update.

spring-data-jpaの@Queryでカスタムオブジェクトを返す

Posted at

Spring Data JPAでgroup byの集計結果などをエンティティではない自前のオブジェクトとして返す。

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")//無意味なクエリだがそこは無視で…
    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();
    }
}

上記のように、結果を保持するための適当なinterfaceを返す。JPQLでもネイティブクエリでもどっちでも使える。

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4