hibernate

Set limit in Hibernate query result

Photo of Ilias TsagklisIlias TsagklisNovember 11th, 2012Last Updated: September 25th, 2013
0 543 3 minutes read

This is an example of how to set limit in Hibernate query result. In order to set limit to a query result in Hibernate we have set the example below:

  • Employee class is the class whose objects will be inserted to the database.
  • InSetLimitInHibernateQueryResult we use the Hibernate API to make the interface with the database.
  • We create a newConfiguration, 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 thegetCurrentSession() API method to obtain the current session.
  • Use thebeginTransaction() 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 a newEmployee object and usesave(Object object) API method ofSession to persist the given transient instances to the database.
  • UsegetTransaction() API method ofSession andcommit() API method of Transaction to commit theTransaction.
  • Use thebeginTransaction() API method again. Now create a newQuery, using thecreateQuery(String queryString) API method of Session, with a given query.
  • UsesetMaxResults(int maxResults) to set the maximum number of rows to retrieve. 
  • Use thelist() API method of Query to get the results.
  • Use againgetTransaction() API method of Session andcommit() API method of Transaction to commit the Transaction.

In the code snippets that follow, you can see theEmployee class and theSetLimitInHibernateQueryResultClass that applies all above steps. You can also take a look at thehibernate.cfg.xml file, that holds all configuration for Hibernate, such as JDBC connection settings, andemployee.hbm.xml file that holds the mapping configuration between the Employee class and the Employee table.

package com.javacodegeeks.snippets.enterprise;import java.util.Date;import java.util.List;import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class SetLimitInHibernateQueryResult {@SuppressWarnings("unchecked")public static void main(String[] args) {SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();Session session = sessionFactory.getCurrentSession();try {session.beginTransaction();for (int i = 0; i < 20; i++) {Employee employee = new Employee();employee.setName("employe_"+i);employee.setSurname("surname_"+i);employee.setTitle("QA Engineer_"+i);employee.setCreated(new Date());session.save(employee);}session.getTransaction().commit();}catch (HibernateException e) {e.printStackTrace();session.getTransaction().rollback();}session = sessionFactory.getCurrentSession();try {session.beginTransaction();Query query = session.createQuery("from Employee");query.setMaxResults(10);List<Employee> employees = (List<Employee>) query.list();if (employees!=null) {System.out.println("Total Results:" + employees.size());for (Employee employee : employees) {System.out.println(employee.getId() + " - " + employee.getName());}}session.getTransaction().commit();}catch (HibernateException e) {e.printStackTrace();session.getTransaction().rollback();}}}

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  <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

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  <hibernate-mapping>    <class name="com.javacodegeeks.snippets.enterprise.Employee" table="employee">  <id name="id" column="id"><generator/>  </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>
CREATE TABLE `companydb`.`employee` (  `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,  `name` VARCHAR(45) NOT NULL,  `surname` VARCHAR(45) NOT NULL,  `title` VARCHAR(45) NOT NULL,  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,  PRIMARY KEY (`id`));

Output:

Total Results:1044 - employe_045 - employe_146 - employe_247 - employe_348 - employe_449 - employe_550 - employe_651 - employe_752 - employe_853 - employe_9

 
This was an example of how to set limit in Hibernate query result.

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Ilias TsagklisIlias TsagklisNovember 11th, 2012Last Updated: September 25th, 2013
0 543 3 minutes read
Photo of Ilias Tsagklis

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor atJava Code Geeks.

Related Articles

Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.