SQL Select, HQL Select Example, HQL Select Query
Posted on: October 31, 2010 at 12:00 AM
In this tutorial we will learn how to use HQL Select statement to load all the customers entity.

HQL Select

In this tutorial we will learn how to use HQL Select statement to load the Entity objects.

The HQL Select query is used to load Entity based on certain criteria or load all the entity from the persistence store (database).

Writing HQL Select query:

Here is the simple HQL Select example that loads all the customer.

String HQL_QUERY = "select c from Customer c";

Here is the complete example of HQL Select statement:

package net.roseindia.hqlexamples;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import net.roseindia.model.*;

 * HQL Select Example In this example we are selecting all the customers from
 * the datastore

public class HQLSelect {

	public static void main(String[] args) throws Exception {
		/** Getting the Session Factory and session */
		SessionFactory factory = HibernateUtil.getSessionFactory();
		Session session = factory.getCurrentSession();
		/** Starting the Transaction */
		Transaction tx = session.beginTransaction();

		// Create Select Clause HQL
		String HQL_QUERY = "select c from Customer c";
		Query query = session.createQuery(HQL_QUERY);
		List result = query.list();
		for (Iterator it = result.iterator(); it.hasNext();) {
			Customer customer = (Customer);
			System.out.println("ID: " + customer.getId());
			System.out.println("Name: " + customer.getCustomerName());
			System.out.println("Phone: " + customer.getCustomerPhone());

		/** Closing Session */

Here is the output of the example when executed:

Hibernate: select as id0_, customer0_.customer_name as customer2_0_, customer0_.customer_phone as customer3_0_ from customers customer0_

ID: 1

Name: Deepak

Phone: 222222222

ID: 2

Name: Ravi

Phone: 6565666877878

ID: 3

Name: John

Phone: 154545655

ID: 4

Name: Dermot

Phone: 455666

ID: 5

Name: Raju

Phone: 5454555

ID: 6

Name: Dinesh

Phone: 455455454

Download HQL Select Source Code

Related Tags for SQL Select, HQL Select Example, HQL Select Query: