JPA : How to convert a native query result set to POJO class collection

后端 未结 21 1499
孤街浪徒
孤街浪徒 2020-11-22 09:23

I am using JPA in my project.

I came to a query in which I need to make join operation on five tables. So I created a native query which returns five fields.

21条回答
  •  孤街浪徒
    2020-11-22 09:34

    The easiest way is to use so projections. It can map query results directly to interfaces and is easier to implement than using SqlResultSetMapping.

    An example is shown below:

    @Repository
    public interface PeopleRepository extends JpaRepository {
    
        @Query(value = "SELECT p.name AS name, COUNT(dp.people_id) AS count " +
            "FROM people p INNER JOIN dream_people dp " +
            "ON p.id = dp.people_id " +
            "WHERE p.user_id = :userId " +
            "GROUP BY dp.people_id " +
            "ORDER BY p.name", nativeQuery = true)
        List findByPeopleAndCountByUserId(@Param("userId") Long userId);
    
        @Query(value = "SELECT p.name AS name, COUNT(dp.people_id) AS count " +
            "FROM people p INNER JOIN dream_people dp " +
            "ON p.id = dp.people_id " +
            "WHERE p.user_id = :userId " +
            "GROUP BY dp.people_id " +
            "ORDER BY p.name", nativeQuery = true)
        Page findByPeopleAndCountByUserId(@Param("userId") Long userId, Pageable pageable);
    
    }
    
    
    
    // Interface to which result is projected
    public interface PeopleDTO {
    
        String getName();
    
        Long getCount();
    
    }
    

    The fields from projected interface must match fields in this entity. Otherwise field mapping might break.

    Also if you use SELECT table.column notation always define aliases matching names from entity as shown in example.

提交回复
热议问题