I know this problem has been around a long time, but the workaround supplied in HHH-3988 doesn't seem to work for everyone. (It didn't for me.) So, I thought I'd share my own workaround...and that is to use a @SqlResultSetMapping. So for the OP's query, annotate an entity (probably the one most logically related to your native query, but it doesn't matter which entity...a shortcoming of the spec in my opinion) as follows:
Code:
@Entity
@SqlResultSetMapping(
name = "myMapping",
columns = {
@ColumnResult(name = "customerCount"),
@ColumnResult(name = "averageSalary")
}
)
public class SomeEntity implements Serializable {
...
}
Then, your query should look like this:
Code:
select count(*) customerCount, avg(customer.salary) averageSalary
from customer
where customer.salary > 1000.0 and customer.salary < 10000;
Then, you need to make sure you reference your mapping when you create your native query:
Code:
...
String sql = "...";
List<Object[]> rowList = entityManager.createNativeQuery(sql, "myMapping").getResultList();
...
You'll notice the aliases,
customerCount and
averageSalary, used in the query match the names used in the corresponding @ColumnResults. It's a shame this issue still exists in 3.5. I'm using 3.5.3-Final myself. Hope this saves someone some time.
- Matt