spring-projects / spring-projects/spring-data-jpa

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

Open
#1,275 0 comments 0 reactions 1 assignee View on GitHub

@odrotbohm is already working on this.

Since Dec 30, 2020.

in: core type: bug
Dominant language
Java
Stars
3.3k
Forks
1.6k
PR merge metrics
No merged PRs in 30d

Description

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)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.