spring-data-jpa icon indicating copy to clipboard operation
spring-data-jpa copied to clipboard

Projection doesn't work when use native query [DATAJPA-919]

Open spring-projects-issues opened this issue 9 years ago • 0 comments

Chris Li opened DATAJPA-919 and commented

I am using Projection feature in my project. I need a query which will have a sub-select statement, so I decide to use native query. But the projection can't work well with native query.

// Query method
@Query(value = "select a.id as id, a.name as name, a.balance as balance from accounts a", nativeQuery = true)
public List<AccountProjection> findAccountProjected();
// The projection interface
public interface AccountProjection  {

    public String getId();

    public String getName();

    public BigDecimal getBalance();
   
}

According to my understanding, the normal projection result is a proxy for HashMap. When you call getBalance() method, the proxy will get the value from HashMap and then convert the result to BigDecimal.

But in my case, the HashMap will be

{id="123", balance="Account Name", name="20000"}

, the root cause is in the ResultProcessor.ProjectingConverter. The source parameter is an Object array, then the key and value for the projection will be mis-set (set name value to the balance key).

private Object getProjectionTarget(Object source) {

  if (source != null && source.getClass().isArray()) {
    source = Arrays.asList((Object[]) source);
  }

  if (source instanceof Collection) {
    return toMap((Collection<?>) source, type.getInputProperties());
  }

  return source;
}		

If I change to the JPQL, the projection works well. And the source in above method is a HashMap, everything is fine.

Is this a defect for the projection feature?


Affects: 1.10.2 (Hopper SR2)

spring-projects-issues avatar Jun 24 '16 06:06 spring-projects-issues