When Simple 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 HQLWhenCaseTest {
/**
* @param args
*/
public static void main ( String [] args ) {
Session session = HibernateUtil.getSessionFactory () .openSession () ;
session.beginTransaction () ;
/* String HQL_QUERY = "select " +
"case " +
"when comp.projectCount > 500 " +
"then 'Big Company' " +
"else 'Small Company' " +
"end" +
", comp.name from Company comp";
*/
String HQL_QUERY = "select comp.name, comp.projectCount, " +
"case " +
"when comp.projectCount > 500 " +
"then 'Big Company' " +
"else 'Small 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, Small Company]
[ABC, 160, Small Company]
[MNO, 670, Big Company]
[IJK, 850, Big Company]
[ART, 850, Big Company]
[RNK, 8478, Big Company]
[AOQ, 4578, Big Company]
[BQO, 487, Small Company]
[CFR, 2487, Big Company]
[CFR, 887, Big Company]