I'm trying to run a simple SQL query containig a group by clause.
HistoryEntity:
@Entity
@NamedNativeQueries(value = {
@NamedNativeQuery(name = HistoryEntity.FIND_ALL_BY_REFERENCE,
query = "SELECT h.id, h.reference, h.lrn "
+ "FROM dataHistory h "
+ "WHERE h.reference = :referenceNumber OR h.lrn = :referenceNumber",
resultSetMapping = HistoryEntity.FIND_ALL_BY_REFERENCE_MAPPING),
@NamedNativeQuery(name = HistoryEntity.FIND_REFERENCE_BY_LRN,
query = "SELECT h.reference as reference "
+ "FROM dataHistory h "
+ "WHERE h.lrn = :lrn "
+ "GROUP BY h.reference",
resultSetMapping = "resultMapping")
})
@SqlResultSetMappings(value = {
@SqlResultSetMapping(name = HistoryEntity.FIND_ALL_BY_REFERENCE_MAPPING, entities = {
@EntityResult(entityClass = HistoryEntity.class, fields = {
@FieldResult(name = "id", column = "id"),
@FieldResult(name = "reference", column = "reference"),
@FieldResult(name = "lrn", column = "lrn")
})
}),
@SqlResultSetMapping(name = "resultMapping", columns = {
@ColumnResult(name = "reference")
})
})
public class HistoryEntity implements Serializable {
/**
* @param referenceNumber Referenz (LRN oder BRN)
* @param brnList Liste von BRNs
*/
public static final String FIND_ALL_BY_REFERENCE = "HistoryEntity.findAllByReference";
public static final String FIND_ALL_BY_REFERENCE_MAPPING = "HistoryEntity.findAllByReferenceMapping";
private Integer id;
private String reference;
private String lrn;
public HistoryEntity() {}
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference= reference;
}
public String getLrn() {
return lrn;
}
public void setLrn(String lrn) {
this.lrn = lrn;
}
In the service class, I execute the query as follow:
Query query = entityManager.createNamedQuery("myQuery");
query.setParameter("lrn", lrn);
List resultList = query.getResultList();
Depending on the result of the query, the list contains java.lang.Character's:
Case 1:
SQL-Result (if I'm running the sql in a sql client):
| Reference |
| 123456780678MMM |
| 123456781678MMM |
| 123456782678MMM |
| 123456783678MMM |
Java-List-Result (in Java Debug View):
[1, 1, 1, 1]
Case 2:
SQL-Result:
| Reference |
| 123456780678MMM |
Java-List-Result:
[1]
I'm looking for a way to run a simple sql query with scalar values (using hibernate/jpa) to get as result a list with the values of the result.
Is there any way to do this without using the criteria api?
If you need more information, let me know!
Many thanks in advance for your help.
Marco