1

I have several sql queries that I simply want to fire at the database. I am using hibernate throughout the whole application, so i would prefer to use hibernate to call this sql queries.

In the example below i want to get count + name, but cant figure out how to get that info when i use createSQLQuery().

I have seen workarounds where people only need to get out a single "count()" from the result, but in this case I am using count() + a column as ouput

SELECT count(*), a.name as count FROM user a
WHERE a.user_id IN (SELECT b.user_id FROM user b)
GROUP BY a.name
HAVING COUNT(*) BETWEEN 2 AND 5;

fyi, the above query would deliver a result like this if i call it directly on the database:

1, John
2, Donald
1, Ralph
...

3 Answers 3

3

Alternatively, you can use

SQLQuery query = session.createSQLQuery("SELECT count(*) as num, a.name as name FROM user a WHERE a.user_id IN (SELECT b.user_id FROM user b) GROUP BY a.name HAVING COUNT(*) BETWEEN 2 AND 5;";

query.addScalar("num", Hibernate.INTEGER).addScalar("name", Hibernate.STRING); 
// you might need to use org.hibernate.type.StandardBasicTypes.INTEGER / STRING 
// for Hibernate v3.6+, 
// see https://hibernate.onjira.com/browse/HHH-5138

List<Object> result = query.list();
// result.get(2*i + 0) -> i-th row num
// result.get(2*i + 1) -> i-th row name

I'm using this in case of time-pressure, imo much faster to code then creating your own beans & transformers.

Cheers!

Jakub

Sign up to request clarification or add additional context in comments.

Comments

0

cheers for the info Thomas, worked wonderful for generating objects

the problem i had with my initial query was that "count" was a reserved word :P when i changed the name to something else it worked.

Comments

0

If your SQL statement looks like this SELECT count(*) as count, a.name as name... you could use setResultTransformer(new AliasToBeanResultTransformer(YourSimpleBean.class)) on your Query.
Where YourSimpleBean has the fields Integer count and String name respectively the setters setCount and setName.
On execution of the query with query.list() hibernate will return a List of YourSimpleBeans.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.