Spring JPA native query with Projection gives “ConverterNotFoundException”

回眸只為那壹抹淺笑 提交于 2019-11-29 13:21:15
Robert Niestroj

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.

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

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

I need to map values from 2 tables and solved like this in Repository file

@Query("select distinct emp.user.id as id, " +
    "concat(emp.user.firstName, ' ',emp.user.lastName, ' ',emp.extensionNumber) as name from NmsEmployee emp " +
    " where emp.domain.id = :domainId and (emp.activeUntil= null or emp.activeUntil > :lLogin) ")
    List<Selectable> getSelcByDomainId( @Param("domainId") Long domainId, @Param("lLogin") ZonedDateTime lLogin);

Where Selectable is

public interface Selectable {
     Long getId();
     String getName();
}
Madhura

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];
     }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!