createNativeQuery 映射到 POJO(非实体)
2022-09-02 10:34:49
乍一看,我有一个简单的问题:
entityManager()
.createNativeQuery("select count(*) as total, select sum(field) as total_sum ... blabla")
我想将选择结果写入POJO,如下所示:
public class AggregateStatsDto {
private int total;
private long totalSum;
// getters, setters, cosntructors
}
实现这一目标的最佳方法是什么?
我可以使用JPA 2.1,并尝试使用@SqlResultSetMapping与@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
}
查询:
AggregateStatsDto result = (AggregateStatsDto) entityManager()
.createNativeQuery("select count(*) as total, select sum(field) as total_sum ... blabla", "AggregateStatsResult")
.getSingleResult();
但是没有运气。似乎无论如何它都想要@Entity。但我只想要一个POJO。
org.hibernate.MappingException: Unknown SqlResultSetMapping [AggregateStatsResult]"
提前致谢!