如何使用 jpa 和 hibernate 将本机查询映射到 POJO class

How to map a native query to POJO class using jpa and hibernate

我在我的项目中同时使用了 JPA 和 hibernate。

我创建了一个查询,其中我对许多表进行了连接操作。所以我创建了一个原生的。我得到的结果在 object[] 列表中,但我希望 将结果自动转换为 java POJO class。 您可以在下面检查查询语法和 POJO java class。

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);

POJOclass

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 查询中调用 class CurrentMeasure 的构造函数。

示例: SELECT NEW <package>.CurrentMeasure(obsp.Identifier, obs.phenomenontimestart, nv.value) FROM ...

新语法在第 11.5 章的 Jboss documentation 中进行了解释。

另一种解决方案是使用 HQL Transformers 来实现相同的结果,而无需求助于构造函数。