Spring JPA native query with Projection gives “ConverterNotFoundException”

后端 未结 5 870
遇见更好的自我
遇见更好的自我 2020-12-10 11:22

I\'m using Spring JPA and I need to have a native query. With that query, I need to get only two fields from the table, so I\'m trying to use Projections. It isn\'t working

相关标签:
5条回答
  • 2020-12-10 12:05

    You can return list of Object Array (List) as return type of the native query method in repository class.

    @Query(
                value = "SELECT [type],sum([cost]),[currency] FROM [CostDetails] " +
                        "where product_id = ? group by [type],[currency] ",
                nativeQuery = true
        )
        public List<Object[]> getCostDetailsByProduct(Long productId);
    
    for(Object[] obj : objectList){
         String type = (String) obj[0];
         Double cost = (Double) obj[1];
         String currency = (String) obj[2];
         }
    
    0 讨论(0)
  • 2020-12-10 12:07

    The query should be using a constructor expression:

    @Query("select new com.example.IdsOnly(t.id, t.otherId) from TestTable t where t.creationDate > ?1 and t.type in (?2)")
    

    And i dont know Lombok, but make sure there is a constructor that takes the two IDs as parameters.

    0 讨论(0)
  • 2020-12-10 12:09

    with spring data you can cut the middle-man and simply define

    public interface IdsOnly {
      Integer getId();
      String getOtherId();
    }
    

    and use a native query like;

    @Query(value = "Id, OtherId from TestTable where CreationDate > ?1 and Type in (?2)", nativeQuery = true)
        public Collection<IdsOnly> findEntriesAfterDate(Date creationDate, List<Integer> types);
    

    check out https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

    0 讨论(0)
  • 2020-12-10 12:09

    JPA 2.1 introduces an interesting ConstructorResult feature if you want to keep it native.

    0 讨论(0)
  • 2020-12-10 12:17
    @Query(value = "select  isler.saat_dilimi as SAAT, isler.deger as DEGER from isler where isler.id=:id", nativeQuery = true) 
    List<Period> getById(@Param("id") Long id);
    
    
    public interface Period{
        Long getDEGER(); 
    
        Long getSAAT();
    
    }
    

    as seen in the example code for native query given above, cast return values to any value like as "SAAT", "DEGER" and then define interface "period" which have getDEGER() and getSAAT(). Even if I have not understand why parameter after get must be uppercase, in lowercase scenario it didn't work properly. ie. interface with getDeger(), getSaat() does not work properly in my case.

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