I have an easy problem at the first glance:
entityManager()
.createNativeQuery("select count(*) as total, select sum(field) as total_sum ... blabla")
And I want to write select result into POJO, like this:
public class AggregateStatsDto {
private int total;
private long totalSum;
// getters, setters, cosntructors
}
What the best way to achieve this?
I can use JPA 2.1 and tried to use @SqlResultSetMapping in conjuction with @ConstructorResult:
@SqlResultSetMapping(name = "AggregateStatsResult", classes = {
@ConstructorResult(targetClass = AggregateStatsDto.class,
columns = {
@ColumnResult(name = "total"),
@ColumnResult(name = "totalSum")
})
})
public class AggregateStatsDto {
private long total;
private int totalSum;
// getters, setters, cosntructors
}
Query:
AggregateStatsDto result = (AggregateStatsDto) entityManager()
.createNativeQuery("select count(*) as total, select sum(field) as total_sum ... blabla", "AggregateStatsResult")
.getSingleResult();
But no luck. It seems that it wants @Entity anyway. But I want just a POJO.
org.hibernate.MappingException: Unknown SqlResultSetMapping [AggregateStatsResult]"
Thanks in advance!
Solution: JPA supports @SqlResultSetMappings which you can use to map the query result to a POJO. The following code snippet shows an example of such a mapping. The @ConstructorResult annotation defines a constructor call of the BookValue class.
The easiest way to map a query result to an entity is to provide the entity class as a parameter to the createNativeQuery(String sqlString, Class resultClass) method of the EntityManager and use the default mapping.
Create ad-hoc native queries Creating an ad-hoc native query is quite simple. The EntityManager interface provides the createNativeQuery method for it. It returns an implementation of the Query interface, which is the same that you get when you call the createQuery method to create a JPQL query.
Put your @SqlResultSetMapping annotation in a class which is an actual entity, not in the DTO Class. Your entity manager can not discover your mapping when you annotate a SqlResultSetMapping in a non-entity.
@SqlResultSetMapping(name = "AggregateStatsResult", classes = {
@ConstructorResult(targetClass = AggregateStatsDto.class,
columns = {
@ColumnResult(name = "total"),
@ColumnResult(name = "totalSum")
})
})
@Entity
public class SomeOtherClassWhichIsAnEntity {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With