Scalar Query2
The following example shows how to execute native SQLs.
It returns a List of Object arrays (Object[]) with scalar values for specified columns in the query.
Hibernate uses ResultSetMetadata to determine the type of the returned scalar values.
Refer first example for the configuration and mapping.
package com.bethecoder.tutorials.hibernate.basic.native_queries;
import java.util.Arrays;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;
public class ScalarQueryTest2 {
/**
* @param args
*/
public static void main ( String [] args ) {
Session session = HibernateUtil.getSessionFactory () .openSession () ;
session.beginTransaction () ;
Query query = session.createSQLQuery ( "SELECT id, name, empcnt FROM company" ) ;
List<?> rows = query.list () ;
System.out.println ( "Selected row count : " + rows.size ()) ;
for ( Object row : rows ) {
System.out.println ( Arrays.toString (( Object []) row )) ;
}
session.getTransaction () .commit () ;
session.close () ;
}
}
It gives the following output,
Selected row count : 10
[1, PQR, 3430]
[2, ABC, 23430]
[3, MNO, 26790]
[4, IJK, 67890]
[5, ART, 67890]
[6, RNK, 98890]
[7, AOQ, 97890]
[8, BQO, 9778]
[9, CFR, 478]
[10, CFR, 6478]