Search code examples
javahibernatenamed-query

Hibernate Named Query with Aggregate function


I am trying to execute a named query in Hibernate. The query is defined in this mapping file:

<?xml version="1.0"?>

<class name="MxePosition" table="MY_TABLE">
    <id name="id" column="MY_ID" />
    <property name="quantity" />
    <property name="instrument" />
</class>

<sql-query name="getPositionsForPortfolio">
    <return alias="position" class="com.example.domain.MxePosition"/>
    <![CDATA[
        SELECT 
        SUM(LEG_ONE_NOMINAL) AS {position.quantity}, 
        ID_INSTRUMENT AS {position.instrument} 
        FROM MY_TABLE WHERE SRC_PORTFOLIO= :portfolio GROUP BY ID_INSTRUMENT
    ]]>
</sql-query>

The MxePosition class is as follows:

public class MxePosition {

private Long id;
private String instrument;
private double quantity;

public String getInstrument() {
    return instrument;
}
public void setInstrument(String instrument) {
    this.instrument = instrument;
}
public double getQuantity() {
    return quantity;
}
public void setQuantity(double quantity) {
    this.quantity = quantity;
}
public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
}
}

What I am trying to do is get the named query to return the sum of one column grouped by another column. However, Hibernate is throwing an error which I suspect is because the query result doesn't contain the ID column.

18:06:44,728 ERROR JDBCExceptionReporter:101 - Column not found: MY1_1_0_

Is there a way round this? It must be possible within Hibernate to execute a query containing a GROUP BY clause without including the ID in the result.

I am open to other suggestions not using a named query if there is a better way.


Solution

  • You could simply add a "random" Id to the Query result set and make Hibernate happy i.e.

        SELECT
        MAX(YOUR_ID_COLUMN) AS {position.id}, 
        SUM(LEG_ONE_NOMINAL) AS {position.quantity}, 
        ID_INSTRUMENT AS {position.instrument} 
        FROM MY_TABLE WHERE SRC_PORTFOLIO= :portfolio GROUP BY ID_INSTRUMENT