JPA Data Repositories with SqlResultSetMapping and native queries

前端 未结 3 1990
梦如初夏
梦如初夏 2020-12-16 14:19

I was stuck with the following situation:

My entities are related to each other, but in such a way that i could not use JPQL. I was forced to use native SQL. Now I w

相关标签:
3条回答
  • 2020-12-16 14:57

    Add the missing resultClass

    @NamedNativeQuery(name = "findAllDataMapping", resultClass = Entity.class, query="sql")
    

    Or

    @NamedNativeQuery(name = "findAllDataMapping", resultClass = MyVO.class, resultSetMapping ="findAllDataMapping" query = "sql")
    

    and lastly call the query in your repository

    @Query(nativeQuery = true, name = "findAllDataMapping")
    List<MyVO> findAllOfMyVO(@Param("param1") String param1, @Param("param2") String param2);
    
    0 讨论(0)
  • 2020-12-16 15:00

    You need to mark your query as a query :) And you need to use MyVO instead of MyEntity, because that is the entity you have your resulsts mapped to

    @Repository
    public interface MyRepository extends JpaRepository<MyVO, Long> {
    
        @Query(nativeQuery = true)
        List<MyVO> findAllOfMyVO(@Param("param1") String param1, @Param("param2") String param2);
    }
    
    0 讨论(0)
  • 2020-12-16 15:16

    You are almost there, but for the below parts

    1. The whole @SqlResultSetMapping and @NamedNativeQuery has to be present in the Entity and not the value Object. In your case it should be in the MyEntity class and **not ** the MyVO class. This should resolve your exception.
    2. That will still not do. After you do the above, change the below

      @NamedNativeQuery(name = "findAllDataMapping", to
      @NamedNativeQuery(name = "MyEntity.findAllDataMapping",

    3. Finally, in some cases you need to be explicit in your definition of @ColumnResult(name = "userFirstName"). If it is a complex field like ZonedDateTime or Boolean you may have to explicity state @ColumnResult(name = "date_created", type = ZonedDateTime.class).

    Hope that helps.

    0 讨论(0)
提交回复
热议问题