DaveB
DaveB

Reputation: 3083

Hibernate: setParameter in sum()

Basic hiberate question here, I want to use the sum() aggregate function for a user supplied column, I have tried the query below but it doesnt seem to work, can someone enlighten me?

public Long clientCustomQuery(String option, Date startDate, Date endDate){
    StringBuilder sb = new StringBuilder("select sum(:option) from Session as s ");
    sb.append("where s.date >= :startDate and s.date <= :endDate");
    Query query = this.getEntityManager().createQuery(sb.toString());
    query.setParameter("option", option);
    query.setParameter("startDate", startDate);
    query.setParameter("endDate", endDate);
    return (Long)query.getSingleResult();
}

Thanks

David

Upvotes: 0

Views: 559

Answers (1)

JB Nizet
JB Nizet

Reputation: 691775

You can't use a column name as a query parameter like that. Hibernate doesn't just make a String substitution. It translates the query into a SQL query and uses a prepared statement to bind parameters. And a column name can't be parameterized.

You'll have to do the string substitution yourself:

"select sum(" + option + ") from..."

Side note: using a StringBuilder to concatenate static Strings is useless, and even counter-productive.

Upvotes: 1

Related Questions