dsmyrnaios
dsmyrnaios

Reputation: 325

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

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

}

Upvotes: 1

Views: 3617

Answers (1)

Medhi Redjem
Medhi Redjem

Reputation: 188

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.

Upvotes: 1

Related Questions