2

How can I extract variables total, min, max from hibernate SQL queries and assign them to java variables?

(select count(*) as total, min(price) as min, max(price) as max from product).addScalar("total", Hibernate.INTEGER).addScalar("min", Hibernate.INTEGER).addScalar("max", Hibernate.INTEGER);

2 Answers 2

7

This post should help you.

Later edit:

String sQuery = "select min(myEntity.x), max(myEntity.y) from MyEntity myEntity";
Query hQuery = session.createQuery(sQuery);
List result = hQuery.list();

Iterator iterator = result.iterator();

while (iterator.hasNext()) {
    Object[] row = (Object[])iterator.next();
    for (int col = 0; col < row.length; col++) {
        System.out.println(row[col]);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I want to be able to extract variables from SQL queries, without using criteria if it's possible to do so.
0

Scalar queries return a List of Object arrays (Object[]) - or a single Object[] in your case.

It is however possible to return non-managed entities using a ResultTransformer. Quoting the Hibernate 3.2: Transformers for HQL and SQL blog post:

SQL Transformers

With native sql returning non-entity beans or Map's is often more useful instead of basic Object[]. With result transformers that is now possible.

List resultWithAliasedBean = s.createSQLQuery(
  "SELECT st.name as studentName, co.description as courseDescription " +
  "FROM Enrolment e " +
  "INNER JOIN Student st on e.studentId=st.studentId " +
  "INNER JOIN Course co on e.courseCode=co.courseCode")
  .addScalar("studentName")
  .addScalar("courseDescription")
  .setResultTransformer( Transformers.aliasToBean(StudentDTO.class))
  .list();

StudentDTO dto =(StudentDTO) resultWithAliasedBean.get(0);

Tip: the addScalar() calls were required on HSQLDB to make it match a property name since it returns column names in all uppercase (e.g. "STUDENTNAME"). This could also be solved with a custom transformer that search the property names instead of using exact match - maybe we should provide a fuzzyAliasToBean() method ;)

See also

2 Comments

Never knew about resultTransformers. For now, I'm gonna stick to Object[]. Though, how should queries such as above be tested? I hate publishing it to server run it and time it. Is there a tool lets you test it without delpoying to local server?
@Nishant You can run Hibernate in a Java SE environment (e.g. a test case). Some IDEs are also offering HQL/Criteria editors (e.g. Hibernate Tools in Eclipse).

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.