Reputation: 24334
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.
Upvotes: 0
Views: 4873
Reputation: 24334
I actually found a better solution to this (For my case) not going to work for all cases.
Setting instrument and quantity as a composite key means I can get rid of the ID field entirely. I added this to my mapping XML
<composite-id>
<key-property name="portfolio" />
<key-property name="instrument" />
</composite-id>
I will leave the accepted answer as it helped at the time (and the portfolio column wasnt present in my original question).
Upvotes: 0
Reputation: 14309
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
Upvotes: 1
Reputation: 1617
I think the problem is with your database, not with hibernate. I suspect it will not support using "group by" with an aliased column.
Have you tried:
FROM MY_TABLE WHERE SRC_PORTFOLIO= :portfolio GROUP BY {position.instrument}
Upvotes: 0