【发布时间】:2018-04-14 18:55:20
【问题描述】:
Java、Spring Data JPA
我有 2 个实体:
class Source {
Integer id;
String name;
}
class Item {
Integer id;
String name;
Integer sourceId;
}
我需要这样的统计原生查询结果:
select s.id source_id, s.name source_name, count(i.id) item_count
from source s
left join item i on s.id = i.source_id
group by s.id
我想在 Java 对象 MyResult 中得到结果:
class MyResult {
Source source;
Integer itemCount;
MyResult(Source source, Integer itemCount) {...}
}
最接近的解决方案是像这样使用@SqlResultSetMapping:
@SqlResultSetMapping(
name = "MyResultMapping",
entities = {
@EntityResult(
entityClass = Source.class,
fields = {
@FieldResult(name = "id", column = "source_id"),
@FieldResult(name = "name", column = "source_name"),
}
),
...
???
}
)
或
@SqlResultSetMapping(
name = "MyResultMapping",
classes = {
@ConstructorResult(
targetClass = MyResult.class,
columns = {
@ColumnResult(name = "???"),
???
}
)
}
)
有了第二个变种,我可以使用这样的东西:
MyResult(Integer sourceId, String sourceName, Integer itemsCount) {
this.source = new Source(sourceId, sourceName);
this.itemsCount = itemsCount;
}
但我希望它使用@SqlResultSetMapping 自动化...(因为我的真实对象更复杂)
【问题讨论】:
标签: java spring-data-jpa sqlresultsetmapping hibernate-native-query