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

做~自己de王妃 提交于 2020-01-03 03:07:25

问题


I am using both JPA and hibernate in my project.

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

@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 class

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

}


回答1:


With JPA you can call the constructor of your class CurrentMeasure directly inside your HQL query.

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

The NEW syntax is explained in Jboss documentation at chapter 11.5.

Another solution would be using HQL Transformers to achieve the same result without resorting to a constructor.



来源:https://stackoverflow.com/questions/39155529/how-to-map-a-native-query-to-pojo-class-using-jpa-and-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!