Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Hibernate Hibernate Select Query

 
 

Share on Google+Share on Google+

Hibernate Select Query

Advertisement
This tutorial contain the explanation of Select clause.

Hibernate Select Query

This tutorial contain the explanation of Select clause.

Hibernate Select Clause :

The work of  Select clause is to select whole database record or select the desired record under any condition .It  gathers objects and properties then returns it in a query set.

In hibernate you can use native query or HQL to select records by using SELECT clause. For specific record selection use where clause.

Here we are taking example of employee. So for selecting records of employee table we write query as -

SELECT emp.name, emp.salary, emp.dateOfJoin from Employee emp

This is your select clause, picking the employee details as employee name, salary and date of join from Employee table.

package net.roseindia.main;

import java.util.*;
import net.roseindia.table.Employee;
import net.roseindia.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

public class MainClass {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();

String hql="SELECT emp.name, emp.salary, emp.dateOfJoin from Employee emp";
Query query=session.createQuery(hql);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);

List objectList = query.list();
Iterator iterator = objectList.iterator();
System.out.println("Employee Name \t Salary \t Date of Join");
while(iterator.hasNext()){ 
Map map = (Map)iterator.next();
System.out.print(map.get("0"));
System.out.print("\t\t"+map.get("1"));
System.out.print("\t\t"+map.get("2"));
System.out.println();
}
session.close();
}
}

Output:

Hibernate: select employee0_.name as col_0_0_, employee0_.salary as col_1_0_, employee0_.date_of_join as col_2_0_ from employee employee0_
Employee Name  Salary  Date of Join
Mandy          20000   2010-03-12 00:00:00.0
Som            20000   1999-06-22 00:00:00.0
Mandy          15000   2003-12-23 00:00:00.0
Roxi           220000  2001-02-03 00:00:00.0
Rowdy          20000   2012-06-27 00:00:00.0

Download complete source code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 2, 2012

Related Tutorials

Discuss: Hibernate Select Query  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com