【问题标题】:How to map a native query to POJO class using jpa and hibernate如何使用 jpa 和 hibernate 将本机查询映射到 POJO 类
【发布时间】:2017-01-02 11:46:46
【问题描述】:

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

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

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

}

【问题讨论】:

  • 当 JPQL 可以满足您的需求时,为什么还要使用 SQL 查询? (假设这些表有实体)。

标签: java hibernate jpa pojo


【解决方案1】:

使用 JPA,您可以直接在 HQL 查询中调用类的构造函数 CurrentMeasure

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

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

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

【讨论】:

    猜你喜欢
    • 2018-06-06
    • 2017-04-29
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多