tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Hibernate > Native SQL > Scalar Query3

Scalar Query3 

The following example shows how to execute native SQLs. Hibernate provides addScalar method to specify the column name to query and its datatype. It returns a List of Object arrays (Object[]) with scalar values for specified columns in the query. Refer first example for the configuration and mapping.

File Name  :  
com/bethecoder/tutorials/hibernate/basic/native_queries/ScalarQueryTest3.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.hibernate.basic.native_queries;

import java.util.Arrays;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;

import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;

public class ScalarQueryTest3 {

  /**
   @param args
   */
  public static void main(String[] args) {

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    
    Query query = session.createSQLQuery("SELECT * FROM company")
      .addScalar("id", Hibernate.INTEGER)
      .addScalar("name", Hibernate.STRING)
      .addScalar("empcnt", Hibernate.LONG);
      
    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]


                    Print

   



Books Recommendation

 
 
bl  br