When Complex Expression
The following example shows using HQL when expression.
Refer first example for the configuration and mapping.
package com.bethecoder.tutorials.hibernate.basic.tests;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;
public class HQLWhenCaseTest2 {
/**
* @param args
*/
public static void main ( String [] args ) {
Session session = HibernateUtil.getSessionFactory () .openSession () ;
session.beginTransaction () ;
String HQL_QUERY = "select comp.name, comp.projectCount, " +
"case " +
"when comp.projectCount < 300 " +
"then 'Very Small Company' " +
"when comp.projectCount < 500 " +
"then 'Small Company' " +
"when comp.projectCount < 1000 " +
"then 'Big Company' " +
"else 'Very Big Company' " +
"end" +
" from Company comp" ;
Query query = session.createQuery ( HQL_QUERY ) ;
List<?> rows = query.list () ;
Iterator<?> rowsIt = rows.iterator () ;
Object [] row = null ;
while ( rowsIt.hasNext ()) {
row = ( Object []) rowsIt.next () ;
System.out.println ( Arrays.toString ( row )) ;
}
session.getTransaction () .commit () ;
session.close () ;
}
}
It gives the following output,
[PQR, 220, Very Small Company]
[ABC, 160, Very Small Company]
[MNO, 670, Big Company]
[IJK, 850, Big Company]
[ART, 850, Big Company]
[RNK, 8478, Very Big Company]
[AOQ, 4578, Very Big Company]
[BQO, 487, Small Company]
[CFR, 2487, Very Big Company]
[CFR, 887, Big Company]