In this tutorial, we are going to see how to read data from the database using Hibernate orderby asc or desc manner.
Hibernate orderby:
We can read the orderd data in hibernate in two different ways i.e hibernate criteria API and hibernate HQL language.
Versions:
- Hibernate 5.2.12.Final
- Java 8
Dependency:
<!-- Hibernate 5.2.12 Final -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.12.Final</version>
</dependency>
Hibernate orderby Example:
Hibernate Utility class: Responsible to provide a hibernate session factory object.
package com.onlinetutorialspoint.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
private static StandardServiceRegistry standardServiceRegistry;
private static SessionFactory sessionFactory;
static{
if (sessionFactory == null) try {
standardServiceRegistry = new StandardServiceRegistryBuilder()
.configure()
.build();
MetadataSources metadataSources = new MetadataSources(standardServiceRegistry);
Metadata metadata = metadataSources.getMetadataBuilder().build();
sessionFactory = metadata.getSessionFactoryBuilder().build();
} catch (Exception e) {
e.printStackTrace();
if (standardServiceRegistry != null) {
StandardServiceRegistryBuilder.destroy(standardServiceRegistry);
}
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
1. Hibernate orderby using Criteria API:
Reading data from the database using CriteriaQuery and applying the orderby clause on the criteria query object.
1.1 Orderby using CriteriaQuery on a Single column:
public static void orderByCriteriaQuery(){
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Item> criteriaQuery = builder.createQuery(Item.class);
Root<Item> root = criteriaQuery.from(Item.class);
criteriaQuery.select(root);
criteriaQuery.orderBy(builder.asc(root.get("itemId")));
Query<Item> query = session.createQuery(criteriaQuery);
List<Item> list = query.getResultList();
printItems(list);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printItems(List<Item> itemsList) {
itemsList.forEach(HibernateOrderBy::accept);
}
private static void accept(Item item) {
System.out.print("Item Id : " + item.getItemId());
System.out.print("\t Item Price : " + item.getItemPrice());
System.out.print("\t Item Name : " + item.getItemName()+"\n");
}
Applied orderby asc on itemId.
Output:
Hibernate: select item0_.id as id1_0_, item0_.category as category2_0_, item0_.item_name as item_nam3_0_, item0_.item_price as item_pri4_0_ from item item0_ order by item0_.id asc
Item Id : 1701 Item Price : 15000.0 Item Name : Samsung
Item Id : 1702 Item Price : 12000.0 Item Name : Lenovo
Item Id : 1703 Item Price : 7500.0 Item Name : Hibernate in Action
Item Id : 1704 Item Price : 47500.0 Item Name : Dell
Item Id : 1705 Item Price : 42500.0 Item Name : Lenovo
Item Id : 1706 Item Price : 112500.0 Item Name : Apple Mac Book Pro
Item Id : 1707 Item Price : 82500.0 Item Name : Apple Mac Book Air
Item Id : 1708 Item Price : 1500.0 Item Name : Thinking in Java
Item Id : 1709 Item Price : 2000.0 Item Name : Spring in Action
1.2 Orderby using CriteriaQuery on Multiple columns:
We can even apply the orderby clause on multiple data columns using Order interface.
public static void orderByListCriteriaQuery(){
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Item> criteriaQuery = builder.createQuery(Item.class);
Root<Item> root = criteriaQuery.from(Item.class);
criteriaQuery.select(root);
List<Order> orderList = new ArrayList<>();
orderList.add(builder.asc(root.get("itemName")));
orderList.add(builder.desc(root.get("itemId")));
criteriaQuery.orderBy(orderList);
Query<Item> query = session.createQuery(criteriaQuery);
List<Item> list = query.getResultList();
printItems(list);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printItems(List<Item> itemsList) {
itemsList.forEach(HibernateOrderBy::accept);
}
private static void accept(Item item) {
System.out.print("Item Id : " + item.getItemId());
System.out.print("\t Item Price : " + item.getItemPrice());
System.out.print("\t Item Name : " + item.getItemName()+"\n");
}
Applied orderby asc on itemName and desc on itemId
Output:
Hibernate: select item0_.id as id1_0_, item0_.category as category2_0_, item0_.item_name as item_nam3_0_, item0_.item_price as item_pri4_0_ from item item0_ order by item0_.item_name asc, item0_.id desc
Item Id : 1707 Item Price : 82500.0 Item Name : Apple Mac Book Air
Item Id : 1706 Item Price : 112500.0 Item Name : Apple Mac Book Pro
Item Id : 1704 Item Price : 47500.0 Item Name : Dell
Item Id : 1712 Item Price : 22000.0 Item Name : Google Nexus
Item Id : 1713 Item Price : 22000.0 Item Name : Google Pixel
Item Id : 1703 Item Price : 7500.0 Item Name : Hibernate in Action
Item Id : 1710 Item Price : 90000.0 Item Name : iPhone X
Item Id : 1714 Item Price : 76000.0 Item Name : Lenovi Idea Pod
Item Id : 1705 Item Price : 42500.0 Item Name : Lenovo
Item Id : 1702 Item Price : 12000.0 Item Name : Lenovo
2. Hibernate orderby using HQL:
We can also get the data asc or desc order using hibernate query language.
2.1 Orderby using HQL on a Single column:
Reading items data orderby descending.
public static void orderByDescHQL(){
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
Query query = session.createQuery("From Item i ORDER BY i.id DESC");
List<Item> list = query.getResultList();
printItems(list);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printItems(List<Item> itemsList) {
itemsList.forEach(HibernateOrderBy::accept);
}
private static void accept(Item item) {
System.out.print("Item Id : " + item.getItemId());
System.out.print("\t Item Price : " + item.getItemPrice());
System.out.print("\t Item Name : " + item.getItemName()+"\n");
}
Output:
Hibernate: select item0_.id as id1_0_, item0_.category as category2_0_, item0_.item_name as item_nam3_0_, item0_.item_price as item_pri4_0_ from item item0_ order by item0_.id DESC
Item Id : 1715 Item Price : 700.0 Item Name : Let us C
Item Id : 1714 Item Price : 76000.0 Item Name : Lenovi Idea Pod
Item Id : 1713 Item Price : 22000.0 Item Name : Google Pixel
Item Id : 1712 Item Price : 22000.0 Item Name : Google Nexus
Item Id : 1711 Item Price : 25000.0 Item Name : N+
Item Id : 1710 Item Price : 90000.0 Item Name : iPhone X
Item Id : 1709 Item Price : 2000.0 Item Name : Spring in Action
Item Id : 1708 Item Price : 1500.0 Item Name : Thinking in Java
Item Id : 1707 Item Price : 82500.0 Item Name : Apple Mac Book Air
2.2 Orderby using HQL on multiple columns:
Applying for order by itemId desc, itemPrice desc
public static void orderByHQLMultipleColumns(){
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
Query query = session.createQuery("From Item i ORDER BY i.id DESC, i.itemPrice DESC");
List<Item> list = query.getResultList();
printItems(list);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printItems(List<Item> itemsList) {
itemsList.forEach(HibernateOrderBy::accept);
}
private static void accept(Item item) {
System.out.print("Item Id : " + item.getItemId());
System.out.print("\t Item Price : " + item.getItemPrice());
System.out.print("\t Item Name : " + item.getItemName()+"\n");
}
Output:
Hibernate: select item0_.id as id1_0_, item0_.category as category2_0_, item0_.item_name as item_nam3_0_, item0_.item_price as item_pri4_0_ from item item0_ order by item0_.id DESC, item0_.item_price DESC
Item Id : 1715 Item Price : 700.0 Item Name : Let us C
Item Id : 1714 Item Price : 76000.0 Item Name : Lenovi Idea Pod
Item Id : 1713 Item Price : 22000.0 Item Name : Google Pixel
Item Id : 1712 Item Price : 22000.0 Item Name : Google Nexus
Item Id : 1711 Item Price : 25000.0 Item Name : N+
Item Id : 1710 Item Price : 90000.0 Item Name : iPhone X
Item Id : 1709 Item Price : 2000.0 Item Name : Spring in Action
Item Id : 1708 Item Price : 1500.0 Item Name : Thinking in Java
Item Id : 1707 Item Price : 82500.0 Item Name : Apple Mac Book Air
References:
Happy Learning 🙂