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

Result Transformer 

The following example shows how to use Result Transformer with Native SQL queries. Refer first example for the configuration and mapping.

File Name  :  
com/bethecoder/tutorials/hibernate/basic/native_queries/ResultTransformerTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.hibernate.basic.native_queries;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;

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

public class ResultTransformerTest {

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

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    
    Query query = session.createSQLQuery("SELECT id, name FROM company");
    query.setResultTransformer(Transformers.aliasToBean(CompanyShortInfo.class));
    
    List<CompanyShortInfo> companies = query.list();    
    System.out.println("Selected row count : " + companies.size());
    
    for (CompanyShortInfo company : companies) {
      System.out.println(company);
    }
    
    session.getTransaction().commit();
    session.close();
  }
  
}
   

It gives the following output,
Selected row count : 10
CompanyShortInfo[1, PQR]
CompanyShortInfo[2, ABC]
CompanyShortInfo[3, MNO]
CompanyShortInfo[4, IJK]
CompanyShortInfo[5, ART]
CompanyShortInfo[6, RNK]
CompanyShortInfo[7, AOQ]
CompanyShortInfo[8, BQO]
CompanyShortInfo[9, CFR]
CompanyShortInfo[10, CFR]



 
  


  
bl  br