Order query resultset in Hibernate with Criteria
This is an example of how to order a query resultset in Hibernate with Criteria
. In Hibernate, Criteria
is a simplified API for retrieving entities by composing Criterion
objects. This is a very convenient approach for functionality like “search” screens where there is a variable number of conditions to be placed upon the result set. The Session
is a factory for Criteria
. Criterion
instances are usually obtained via the factory methods on Restrictions
. To order a query resultset in Hibernate with Criteria we have set the example below:
Employee
class is the class whose objects will be inserted to the database.- In
OrderQueryResultsetInHibernateWithCriteria
we use the Hibernate API to make the interface with the database. - We create a new
Configuration
, that allows the application to specify properties and mapping documents to be used when creating aSessionFactory
. Usually an application will create a singleConfiguration
, build a single instance ofSessionFactory
and then instantiateSessions
in threads servicing client requests. Usingconfigure()
API method we use the mappings and properties specified in an application resource namedhibernate.cfg.xml
. Then, withbuildSessionFactory()
we instantiate a newSessionFactory
, using the properties and mappings in this configuration. - Use the
getCurrentSession()
API method to obtain the current session. - Use the
beginTransaction()
API method to begin a unit of work and return the associatedTransaction
object. If a new underlying transaction is required, begin the transaction. Otherwise continue the new work in the context of the existing underlying transaction. - Create new
Employee
objects and usesave(Object object)
API method ofSession
to persist the given transient instances to the database. - Use
getTransaction()
API method ofSession
andcommit()
API method of Transaction to commit theTransaction
. - Use the
beginTransaction()
API method again. Now create a newCriteria
, using thecreateCriteria(Class persistentClass)
API method ofSession
for the givenEmployee
class. - Use
addOrder(Order order)
to add ordering to the result set. InOrder
class you can define the type of ordering to apply, for example,asc(String propertyName)
applies an ascending order to the given property. - Use the
list()
API method of Criteria to get the results, after having applied the constraints. - Use again
getTransaction()
API method of Session andcommit()
API method of Transaction to commit theTransaction
.
In the code snippets that follow, you can see the Employee
class and the OrderQueryResultsetInHibernateWithCriteria
Class that applies all above steps. You can also take a look at the hibernate.cfg.xml
file, that holds all configuration for Hibernate, such as JDBC connection settings, and employee.hbm.xml
file that holds the mapping configuration between the Employee
class and the Employee
table.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | package com.javacodegeeks.snippets.enterprise; import java.util.Date; import java.util.List; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Order; public class OrderQueryResultsetInHibernateWithCriteria { @SuppressWarnings ( "unchecked" ) public static void main(String[] args) { SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.getCurrentSession(); try { session.beginTransaction(); Employee employee = new Employee(); employee.setName( "Jack" ); employee.setSurname( "Thomson" ); employee.setTitle( "QA Engineer" ); employee.setCreated( new Date()); session.save(employee); employee = new Employee(); employee.setName( "Helen" ); employee.setSurname( "Jasmin" ); employee.setTitle( "Project Manager" ); employee.setCreated( new Date()); session.save(employee); employee = new Employee(); employee.setName( "Tom" ); employee.setSurname( "Markus" ); employee.setTitle( "Software Developer" ); employee.setCreated( new Date()); session.save(employee); session.getTransaction().commit(); } catch (HibernateException e) { e.printStackTrace(); session.getTransaction().rollback(); } session = sessionFactory.getCurrentSession(); try { session.beginTransaction(); Criteria criteria = session.createCriteria(Employee. class ); criteria.addOrder(Order.asc( "surname" )); List<Employee> employees = (List<Employee>) criteria.list(); if (employees != null ) { System.out.println( "Total Results:" + employees.size()); for (Employee employee : employees) { System.out.println(employee.getId() + " - " + employee.getSurname()); } } session.getTransaction().commit(); } catch (HibernateException e) { e.printStackTrace(); session.getTransaction().rollback(); } } } |
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | package com.javacodegeeks.snippets.enterprise; import java.util.Date; public class Employee { private Long id; private String name; private String surname; private String title; private Date created; public Long getId() { return id; } public void setId(Long id) { this .id = id; } public String getName() { return name; } public void setName(String name) { this .name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this .surname = surname; } public String getTitle() { return title; } public void setTitle(String title) { this .title = title; } public Date getCreated() { return created; } public void setCreated(Date created) { this .created = created; } } |
hibernate.cfg.xml
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | <? xml version = '1.0' encoding = 'utf-8' ?> <! DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" < hibernate-configuration > < session-factory > <!-- JDBC connection settings --> < property name = "connection.driver_class" >com.mysql.jdbc.Driver</ property > < property name = "connection.url" >jdbc:mysql://localhost/companydb</ property > < property name = "connection.username" >jcg</ property > < property name = "connection.password" >jcg</ property > <!-- JDBC connection pool, use Hibernate internal connection pool --> < property name = "connection.pool_size" >5</ property > <!-- Defines the SQL dialect used in Hiberante's application --> < property name = "dialect" >org.hibernate.dialect.MySQLDialect</ property > <!-- Enable Hibernate's automatic session context management --> < property name = "current_session_context_class" >thread</ property > <!-- Disable the second-level cache --> < property name = "cache.provider_class" >org.hibernate.cache.NoCacheProvider</ property > <!-- Display and format all executed SQL to stdout --> < property name = "show_sql" >true</ property > < property name = "format_sql" >true</ property > <!-- Drop and re-create the database schema on startup --> < property name = "hbm2ddl.auto" >update</ property > <!-- Mapping to hibernate mapping files --> < mapping resource = "Employee.hbm.xml" /> </ session-factory > </ hibernate-configuration > |
Employee.hbm.xml
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <? xml version = "1.0" ?> <! DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" < hibernate-mapping > < class name = "com.javacodegeeks.snippets.enterprise.Employee" table = "employee" > < id name = "id" column = "id" > < generator class = "native" /> </ id > < property name = "name" not-null = "true" length = "50" /> < property name = "surname" not-null = "true" length = "50" /> < property name = "title" length = "50" /> < property name = "created" type = "timestamp" /> </ class > </ hibernate-mapping > |
Output:
Total Results:3
2 - Jasmin
3 - Markus
1 - Thomson
This was an example of how to order a query resultset in Hibernate with Criteria
.