Hibernate ORDER BY Clause

In this tutorial you will learn about HQL ORDER BY clause.


 

Ads

Tutorials   
How to write hello world example program in Hibernate? How to create one to one relationship in Hibernate 4 with Annotation? How to calculate minimum in Hibernate using the min() Function Hibernate 4.3.4 Released: Hibernate 4.3.4.Final Maven dependency Hibernate 4.3 Hello World: Example How to create SessionFactory in Hibernate 4.3.1? Hibernate 4 Hello World: Example of Hello World program Hibernate 4 create Session Factory: Example of creating Session Factory in Hibernate 4 Hibernate 4.3 and JPA 2.1 Example What is Hibernate in Java? Hibernate Overview and Architecture What is JPA 2.1? Hibernate 4.3.0.Final Maven dependency Hibernate 4.3 ORM Features Hibernate 4.3 Tutorial Hibernate Criteria average example Hibernate Criteria load all objects from table Hibernate Criteria Hibernate beginner tutorial Hibernate Session.delete() Example Hibernate save or update method example Hibernate Load Example Hibernate save Example - Rose India Hibernate 4 tutorials Hibernate Example Step by Step in Eclipse Hibernate Configuration files Setup Hibernate Environment Hibernate Architecture Hibernate Overview Hibernate 4.2 Tutorial Hibernate 4 Annotations Tutorial Hibernate 4 AnnotationSessionFactoryBean hibernate versions hibernate jndi hibernate tomcat hibernate metamodel generator hibernate entity Seam Hibernate C3P0 Hibernate hibernate shard hibernate means temporal hibernate jsf hibernate spring j2ee hibernate spring hibernate encrypted password alias_to_entity_map hibernate temporal jsf spring hibernate hibernate by example hibernate repository hibernate sample code
Ads

Hibernate ORDER BY Clause

In this tutorial you will learn about HQL ORDER BY clause.

Purpose for using ORDER BY clause is similar to that it is used in SQL to sort the records. By default records are sorted in ascending order to sort records in descending order 'desc' can be used with the query.

Example

Here I am giving a simple example which will demonstrate you how a HQL order by clause can be used. To achieve the solution of such problem at first I have created a table named employee with the field 'Id' and 'Name'. Next created a POJO / Persistent class named Employee to fetch the persistent object, a hibernate.cfg.xml file that the Hibernate can utilize it to create connection pool and the required environment setup, an employee.hbm.xml file to map an Employee object with table employee. And finally create a simple java file into which we will use HQL order by clause for sorting the data from the database.

Complete Code :

Employee.java

package roseindia;

public class Employee {
private int id;
private String name;

public Employee()
{

}
public Employee(String name)
{
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;
}
}

employee.hbm.xml

<?xml version='1.0'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="roseindia">
<class name="Employee" table="employee">
<id name="id" type="int" column="Id" >
<generator class="assigned"/>
</id>
<property name="name">
<column name="Name" />
</property>
</class>
</hibernate-mapping>

HibernateOrderByClause

package roseindia;

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

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateOrderByClause {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

public static void main(String args[]) {
Session session = null;
try {
try {
Configuration cfg = new Configuration().addResource(
"roseindia/employee.hbm.xml").configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);

} catch (Throwable th) {
System.err.println("Failed to create sessionFactory object."
+ th);
throw new ExceptionInInitializerError(th);
}
session = sessionFactory.openSession();
Query orderByClause = session
.createQuery("select emp from Employee emp order by emp.name");
List<Employee> empList = orderByClause.list();
System.out.println("Displaying id from table employee");
Iterator<Employee> it = empList.iterator(); //orderByClause.iterate();
System.out.println("Id \t Name");
while(it.hasNext())
{
Employee emp = (Employee)it.next();
System.out.println(emp.getId() +"\t"+ emp.getName()); 
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
session.close();
}
}
}

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.10.13:3306/data
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>

</hibernate-configuration>

Output :

1. Data in a table Employee is as :

2. When you will execute the java file HibernateOrderByClause.java (RightClick -> run as -> Java Application) data of table employee will be displayed in console in the ascending order by name as :

Download Source Code

Advertisements

Share on Google+Share on Google+

Hibernate ORDER BY Clause

Posted on: February 24, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

 

Discuss: Hibernate ORDER BY Clause  

Post your Comment


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

Ads

 

Ads