tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Hibernate > Hibernate Query Language > Access Properties As Object

Access Properties As Object 

The following example shows accessing individual properties of entity as an object. Each row with matching condition will be returned as an instance of specified class. This class should have a constructor with same parameters as the properties in the query. Refer first example for the configuration and mapping.

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

import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import com.bethecoder.tutorials.hibernate.basic.CompanyShortInfo;
import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;

public class HQLAccessPropsAsObjectTest {

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

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    
    String HQL_QUERY = 
      "select new com.bethecoder.tutorials.hibernate.basic.CompanyShortInfo(comp.id, comp.name)" 
      " from Company comp where comp.employeeCount >= 23430";
    
    List<CompanyShortInfo> rows = (List<CompanyShortInfo>session.createQuery(HQL_QUERY).list();    
    
    System.out.println("Selected row count : " + rows.size());
    Iterator<CompanyShortInfo> rowsIt = rows.iterator();
    
    while (rowsIt.hasNext()) {
      System.out.println(rowsIt.next());
    }
    
    session.getTransaction().commit();
    session.close();
  }

}
   

CompanyShortInfo class with minimal information from Company class.

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

public class CompanyShortInfo {

  private int id;
  private String name;
  
  public CompanyShortInfo(int id, String name) {
    super();
    this.id = id;
    this.name = name;
  }
  
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String toString() {
    return "CompanyShortInfo[" + id + ", " + name + "]";
  }
}
   

It gives the following output,
Selected row count : 6
CompanyShortInfo[2, ABC]
CompanyShortInfo[3, MNO]
CompanyShortInfo[4, IJK]
CompanyShortInfo[5, ART]
CompanyShortInfo[6, RNK]
CompanyShortInfo[7, AOQ]


                    Print

   



Books Recommendation

 
 
bl  br