Online Training Spring Hibernate Training in Delhi R Programming Training Course Big Data and Hadoop Training Java Training

Hibernate Criteria Ordering Example

In this tutorial you will learn about the Hibernate Criteria Projection Ordering.

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 Criteria Ordering Example

In this tutorial you will learn about the Hibernate Criteria Projection Ordering.

In Hibernate Criteria query to arrange the result set in ascending or descending order a method addOrder(Order.asc|desc()) is used.

Example

In the example given below I have used the order both ascending and descending. To order the result set in specific ordering system I have list the field first using Projections.projectionList() method in setProjection() method you can specify the number of columns by using the Projections.projectionList().add(Projections.property()) and added the properties that I want to display using the method add(Projections.property()) method then added the addOrder(Order.asc|desc()) method for ordering the projections. Then as an output displayed the list on console in their specific order.

Table goodsdealer

CREATE TABLE `goodsdealer` ( 
`goodsDealerId` int(15) NOT NULL, 
`orderedGoodsName` varchar(15) default NULL, 
`numOfGoodsOrder` int(20) default NULL, 
`priceOfGoods` int(10) default NULL 
) ENGINE=InnoDB DEFAULT CHARSET=latin1

GoodsDealer.java

package roseindia;

public class GoodsDealer {
private int goodsDealerId;
private int numOfGoodsOrder; 
private int priceOfGoods;
private String orderedGoodsName; 

public GoodsDealer()
{
super();
}
public GoodsDealer(int priceOfGoods, int goodsDealerId, int numOfGoodsOrder, String 
orderedGoodsName)
{ 
this.priceOfGoods = priceOfGoods;
this.goodsDealerId = goodsDealerId;
this.numOfGoodsOrder = numOfGoodsOrder;
this.orderedGoodsName = orderedGoodsName;
}
public int getPriceOfGoods() {
return priceOfGoods;
}
public void setPriceOfGoods(int priceOfGoods) {
this.priceOfGoods = priceOfGoods;
}
public int getGoodsDealerId() {
return goodsDealerId;
}
public void setGoodsDealerId(int goodsDealerId) {
this.goodsDealerId = goodsDealerId;
}
public int getNumOfGoodsOrder() {
return numOfGoodsOrder;
}
public void setNumOfGoodsOrder(int numOfGoodsOrder) {
this.numOfGoodsOrder = numOfGoodsOrder;
}
public String getOrderedGoodsName() {
return orderedGoodsName;
}
public void setOrderedGoodsName(String orderedGoodsName) {
this.orderedGoodsName = orderedGoodsName;
}
}

GoodsDealer.hbm.xml

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

<hibernate-mapping package="roseindia">
<class name= "GoodsDealer" table="goodsdealer">
<id name= "goodsDealerId" type="int" column="goodsDealerId">
</id>
<property name="numOfGoodsOrder">
<column name="numOfGoodsOrder"/>
</property>
<property name="orderedGoodsName">
<column name="orderedGoodsName"/>
</property>
<property name="priceOfGoods">
<column name="priceOfGoods"/>
</property>
</class>

</hibernate-mapping>

HibernateCriteriaOrderingExample.java

package roseindia;

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

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateCriteriaOrderingExample {
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/GoodsDealer.hbm.xml");
cfg.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();
Criteria criteria = session.createCriteria(GoodsDealer.class);
// To order the rows in ascending order
criteria.setProjection(Projections.projectionList()
.add(Projections.property("numOfGoodsOrder"))
.add(Projections.property("priceOfGoods")))
.addOrder(Order.asc("numOfGoodsOrder"));
// To order the rows in descending order
// criteria.setProjection(Projections.projectionList()
// .add(Projections.property("numOfGoodsOrder"))
// .add(Projections.property("priceOfGoods")))
// .addOrder(Order.desc("numOfGoodsOrder"));
List order = criteria.list();
Iterator it = order.iterator();
System.out.println("numOfGoodsOrder priceOfGoods");
while(it.hasNext())
{
Object[] obj = (Object[])it.next();
System.out.println(obj[0]+"\t\t "+obj[1]);
}
}
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. table goodsdealer

2. When you will execute the HibernateCriteriaOrderingExample.java file (RightClick -> RunAs -> Java Application) the following queries respective to both ascending and descending and the output will be displayed on console as :

Hibernate Query for ascending order

INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Mar 21, 2012 6:54:21 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select this_.numOfGoodsOrder as y0_, this_.priceOfGoods as y1_ from goodsdealer this_ order by this_.numOfGoodsOrder asc

2.1 Output of ascending order list is as follows :

Hibernate Query for descending order

INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Mar 21, 2012 7:48:07 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select this_.numOfGoodsOrder as y0_, this_.priceOfGoods as y1_ from goodsdealer this_ order by this_.numOfGoodsOrder desc

2.2 Output of descending order list is as follows :

Download Source Code

Advertisements

Share on Google+Share on Google+

Hibernate Criteria Ordering Example

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

Advertisements

Ads
 

Discuss: Hibernate Criteria Ordering Example  

Post your Comment


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

Ads

 

Ads