Wednesday, October 05, 2011

SQL Restriction In Hibernate Criteria Query

Here is an example to add a SQL Restriction in hibernate Criteria query.
Let's consider we have
  • A Student.java entity
  • A stored procedure in place which returns total marks obtained by a student in each subject.
public Class Student {
    private Integer id;
    private String name;
    .
    .
    //getters & setters methods
}
Assuming get_marks() stored procedure will result records in following format.

id Maths Enlish Science
1 78 75 23
2 74 70 97
I want to list down the Students who has got more than 90 in Maths. Here goes the Hibernate Criteria query.
Criteria c = session.createCriteria(Student.class)
		.addSqlrestriction(" {alias}.id in (SELECT id FROM get_marks() WHERE maths_total > ? ) ", new Double(90.0), Hibernate.Double);

In above statement {alias}.id will refer to the id column of Student table. The above addSqlrestriction example shows the SQL restriction statement with only one parameter.
What if you have to pass multiple arguments?
In such cases you need to pass array of Objects & array of Type as second & third parameter to the addSqlrestriction(String, Object[], Type[]). And in SQL String have ? where ever argument is required, as shown in above example.

I hope this helps.
Thanks.