如何使用jpa和hibernate将本机查询映射到POJO类 [英] How to map a native query to POJO class using jpa and hibernate
问题描述
我在我的项目中使用JPA和hibernate。
I am using both JPA and hibernate in my project.
我创建了一个查询,其中我在许多表上进行了连接操作。所以我创建了一个原生的。我得到的结果是在object []的列表中,但我希望将结果自动转换为java POJO类。
你可以查看下面的查询语法和POJO java类。
I have created a query in which i made join operation on many tables. So I created a native one. The results that i get are in a list of object[] but i would like the results to be converted automatically to a java POJO class. You can check both the query syntax and POJO java class below.
JPA查询
@Query(value = "SELECT obsp.Identifier, obs.phenomenontimestart, nv.value " +
"From Series s " +
"INNER JOIN Featureofinterest fi on s.featureofinterestid = fi.featureofinterestid " +
"INNER JOIN ObservableProperty obsp on s.observablepropertyid = obsp.ObservablePropertyId " +
"INNER JOIN Observation obs on s.seriesid = obs.seriesid " +
"INNER JOIN NumericValue nv on nv.observationid = obs.observationid " +
"where fi.identifier = ?1 and obs.phenomenontimestart >= ?2 AND obs.phenomenontimestart <= ?3 " +
"order by obs.phenomenontimestart",
nativeQuery = true)
List<CurrentMeasure> findCurrentMeasure(String ident, Timestamp t1, Timestamp t2);
POJO类
public class CurrentMeasure {
private String identifier;
private Timestamp dateTime;
private BigDecimal bigDecimal;
public CurrentMeasure() {
}
public CurrentMeasure(String identifier, Timestamp dateTime, BigDecimal bigDecimal) {
this.identifier = identifier;
this.dateTime = dateTime;
this.bigDecimal = bigDecimal;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public Timestamp getDateTime() {
return dateTime;
}
public void setDateTime(Timestamp dateTime) {
this.dateTime = dateTime;
}
public BigDecimal getBigDecimal() {
return bigDecimal;
}
public void setBigDecimal(BigDecimal bigDecimal) {
this.bigDecimal = bigDecimal;
}
}
推荐答案
使用JPA,您可以直接在HQL查询中调用类 CurrentMeasure
的构造函数。
With JPA you can call the constructor of your class CurrentMeasure
directly inside your HQL query.
示例:
SELECT NEW< package> .CurrentMeasure(obsp.Identifier,obs.phenomenontimestart,nv.value)FROM ...
Jboss文档在第11.5章。
另一个解决方案是使用 HQL变形金刚实现相同的结果没有求助于构造函数。
Another solution would be using HQL Transformers to achieve the same result without resorting to a constructor.
这篇关于如何使用jpa和hibernate将本机查询映射到POJO类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!