Hibernate Criteria Example Tutorial

Filed Under: Hibernate

Welcome to the Hibernate Criteria Example Tutorial. Today we will look into Criteria in Hibernate.

Hibernate Criteria

criteria in hibernate, hibernate criteria example, hibernate criteria, hibernate criteria join, hibernate criteria query

Most of the times, we use HQL for querying the database and getting the results. HQL is not preferred way for updating or deleting values because then we need to take care of any associations between tables.

Hibernate Criteria API provides object oriented approach for querying the database and getting results. We can’t use Criteria in Hibernate to run update or delete queries or any DDL statements. Hibernate Criteria query is only used to fetch the results from the database using object oriented approach.

For my Hibernate criteria example, I will use the same setup as in my HQL Example and show you how to use Criteria in Hibernate for querying databases.

Some of the common usage of Hibernate Criteria API are;

  1. Hibernate Criteria API provides Projection that we can use for aggregate functions such as sum(), min(), max() etc.
  2. Hibernate Criteria API can be used with ProjectionList to fetch selected columns only.
  3. Criteria in Hibernate can be used for join queries by joining multiple tables, useful methods for Hibernate criteria join are createAlias(), setFetchMode() and setProjection()
  4. Criteria in Hibernate API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.
  5. Hibernate Criteria API provides addOrder() method that we can use for ordering the results.

Below class shows different usages of Hibernate Criteria API, most of these are replacements of examples in HQL tutorial.


package com.journaldev.hibernate.main;

import java.util.Arrays;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.journaldev.hibernate.model.Employee;
import com.journaldev.hibernate.util.HibernateUtil;

public class HibernateCriteriaExamples {

	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		// Prep work
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.getCurrentSession();
		Transaction tx = session.beginTransaction();

		//Get All Employees
		Criteria criteria = session.createCriteria(Employee.class);
		List<Employee> empList = criteria.list();
		for(Employee emp : empList){
			System.out.println("ID="+emp.getId()+", Zipcode="+emp.getAddress().getZipcode());
		}
		
		// Get with ID, creating new Criteria to remove all the settings
		criteria = session.createCriteria(Employee.class)
					.add(Restrictions.eq("id", new Long(3)));
		Employee emp = (Employee) criteria.uniqueResult();
		System.out.println("Name=" + emp.getName() + ", City="
				+ emp.getAddress().getCity());

		//Pagination Example
		empList = session.createCriteria(Employee.class)
					.addOrder(Order.desc("id"))
					.setFirstResult(0)
					.setMaxResults(2)
					.list();
		for(Employee emp4 : empList){
			System.out.println("Paginated Employees::"+emp4.getId()+","+emp4.getAddress().getCity());
		}

		//Like example
		empList = session.createCriteria(Employee.class)
				.add(Restrictions.like("name", "%i%"))
				.list();
		for(Employee emp4 : empList){
			System.out.println("Employees having 'i' in name::"+emp4.getName()+","+emp4.getAddress().getCity());
		}
		
		//Projections example
		long count = (Long) session.createCriteria(Employee.class)
				.setProjection(Projections.rowCount())
				.add(Restrictions.like("name", "%i%"))
				.uniqueResult();
		System.out.println("Number of employees with 'i' in name="+count);

		//using Projections for sum, min, max aggregation functions
		double sumSalary = (Double) session.createCriteria(Employee.class)
			.setProjection(Projections.sum("salary"))
			.uniqueResult();
		System.out.println("Sum of Salaries="+sumSalary);
		
		//Join example for selecting few columns
		criteria = session.createCriteria(Employee.class, "employee");
		criteria.setFetchMode("employee.address", FetchMode.JOIN);
		criteria.createAlias("employee.address", "address"); // inner join by default

		ProjectionList columns = Projections.projectionList()
						.add(Projections.property("name"))
						.add(Projections.property("address.city"));
		criteria.setProjection(columns);

		List<Object[]> list = criteria.list();
		for(Object[] arr : list){
			System.out.println(Arrays.toString(arr));
		}
		
		
		// Rollback transaction to avoid messing test data
		tx.commit();
		// closing hibernate resources
		sessionFactory.close();
	}

}

When we execute above Hibernate Criteria example program, we get following output.


May 26, 2014 6:53:32 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
May 26, 2014 6:53:32 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
May 26, 2014 6:53:32 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 26, 2014 6:53:32 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 26, 2014 6:53:32 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: hibernate.cfg.xml
May 26, 2014 6:53:32 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: hibernate.cfg.xml
May 26, 2014 6:53:32 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
May 26, 2014 6:53:32 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Hibernate Configuration loaded
Hibernate serviceRegistry created
May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/TestDB]
May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=pankaj, password=****}
May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
May 26, 2014 6:53:32 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
May 26, 2014 6:53:32 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
May 26, 2014 6:53:32 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select this_.emp_id as emp_id1_1_1_, this_.emp_name as emp_name2_1_1_, this_.emp_salary as emp_sala3_1_1_, address2_.emp_id as emp_id1_0_0_, address2_.address_line1 as address_2_0_0_, address2_.city as city3_0_0_, address2_.zipcode as zipcode4_0_0_ from EMPLOYEE this_ left outer join ADDRESS address2_ on this_.emp_id=address2_.emp_id
ID=1, Zipcode=95129
ID=2, Zipcode=95051
ID=3, Zipcode=560100
ID=4, Zipcode=100100
Hibernate: select this_.emp_id as emp_id1_1_1_, this_.emp_name as emp_name2_1_1_, this_.emp_salary as emp_sala3_1_1_, address2_.emp_id as emp_id1_0_0_, address2_.address_line1 as address_2_0_0_, address2_.city as city3_0_0_, address2_.zipcode as zipcode4_0_0_ from EMPLOYEE this_ left outer join ADDRESS address2_ on this_.emp_id=address2_.emp_id where this_.emp_id=?
Name=Lisa, City=Bangalore
Hibernate: select this_.emp_id as emp_id1_1_1_, this_.emp_name as emp_name2_1_1_, this_.emp_salary as emp_sala3_1_1_, address2_.emp_id as emp_id1_0_0_, address2_.address_line1 as address_2_0_0_, address2_.city as city3_0_0_, address2_.zipcode as zipcode4_0_0_ from EMPLOYEE this_ left outer join ADDRESS address2_ on this_.emp_id=address2_.emp_id order by this_.emp_id desc limit ?
Paginated Employees::4,New Delhi
Paginated Employees::3,Bangalore
Hibernate: select this_.emp_id as emp_id1_1_1_, this_.emp_name as emp_name2_1_1_, this_.emp_salary as emp_sala3_1_1_, address2_.emp_id as emp_id1_0_0_, address2_.address_line1 as address_2_0_0_, address2_.city as city3_0_0_, address2_.zipcode as zipcode4_0_0_ from EMPLOYEE this_ left outer join ADDRESS address2_ on this_.emp_id=address2_.emp_id where this_.emp_name like ?
Employees having 'i' in name::David,Santa Clara
Employees having 'i' in name::Lisa,Bangalore
Hibernate: select count(*) as y0_ from EMPLOYEE this_ where this_.emp_name like ?
Number of employees with 'i' in name=2
Hibernate: select sum(this_.emp_salary) as y0_ from EMPLOYEE this_
Sum of Salaries=1000.0
Hibernate: select this_.emp_name as y0_, address1_.city as y1_ from EMPLOYEE this_ inner join ADDRESS address1_ on this_.emp_id=address1_.emp_id
[Pankaj, San Jose]
[David, Santa Clara]
[Lisa, Bangalore]
[Jack, New Delhi]
May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost/TestDB]

Since I am using HQL example project, you would need to import that and then add this class for it to be working.

Notice the hibernate queries executed in the output, this way you can refine your queries and get the results you are looking for. That’s all for a quick roundup on Criteria in Hibernate.

Comments

  1. mahesh says:

    Finding very difficult to understand….can anyone please give a clear example on query building using StringBuffer on hashMap…. like below….

    StringBuilder query = new StringBuilder();
    StringBuilder queryBuilder = new StringBuilder();
    StringBuilder query2 = new StringBuilder();
    StringBuilder sb = new StringBuilder();
    StringBuilder csb = new StringBuilder();
    Query countQuery;
    Long resultCount;
    StringBuilder countQueryStr = new StringBuilder();
    countQueryStr.append(“SELECT COUNT(master.id) “);
    List resultList = null;
    Query resultQuery;
    RemittanceTransactionMasterVO remittanceTransactionMasterVO = new RemittanceTransactionMasterVO();
    Map parameterizedMap = new HashMap();
    Map detailMap = new HashMap();
    Map<String, List> parameterListMap = new HashMap();

    sb.append(“from RemittanceTransactionMasterVO master left join fetch master.adCodeId ad ”
    + “left join fetch ad.bankCodeId bank left join fetch master.remittanceCurrencyId rmCurrency ”
    + “left join fetch master.remitterCountryId rmCountry left join fetch master.remitterBankCountryId rmBankCntry “);
    if (!StringUtils.isBlank(searchMasterDTO.getDetailIRMNumber())) {
    sb.append(” left join fetch master.remittanceTransactionDetailVOList detail”);

    }
    csb.append(“from RemittanceTransactionMasterVO master left join master.adCodeId ad ”
    + “left join ad.bankCodeId bank left join master.remittanceCurrencyId rmCurrency ”
    + “left join master.remitterCountryId rmCountry left join master.remitterBankCountryId rmBankCntry “);
    if (!StringUtils.isBlank(searchMasterDTO.getDetailIRMNumber())) {
    csb.append(” left join master.remittanceTransactionDetailVOList detail”);

    }
    query.append(” where “);
    if (fromDate != null && toDate != null) {
    query.append(” master.remittanceDate >= :REMITTANCEDATE1 and “);
    parameterizedMap.put(“REMITTANCEDATE1″, fromDate);
    query.append(” master.remittanceDate = :ADDEDDATE1 and “);
    parameterizedMap.put(“ADDEDDATE1″, searchMasterDTO.getFromAddedDate());
    query.append(” master.addedDate <= :ADDEDDATE2 and ");
    parameterizedMap.put("ADDEDDATE2", com.htc.edis.util.DateUtils.addEndTimeForDate(searchMasterDTO.getToAddedDate()));
    }
    if (searchMasterDTO.getRemittanceReferenceNumberArray() != null && searchMasterDTO.getRemittanceReferenceNumberArray().length != 0) {
    query.append(" master.remittanceReferenceNumber in (");
    for (int i = 0; i < searchMasterDTO.getRemittanceReferenceNumberArray().length; i++) {
    if (searchMasterDTO.getRemittanceReferenceNumberArray().length == 1) {
    query.append(" :REMITTANCEREFERENCENUMBER" + i);
    } else {
    query.append(" :REMITTANCEREFERENCENUMBER" + i);
    if (searchMasterDTO.getRemittanceReferenceNumberArray().length != i + 1) {
    query.append(" , ");
    }
    }
    parameterizedMap.put("REMITTANCEREFERENCENUMBER" + i, searchMasterDTO.getRemittanceReferenceNumberArray()[i]);
    }
    query.append(") and");
    }
    if (searchMasterDTO.getDetailIRMNumberArray() != null && searchMasterDTO.getDetailIRMNumberArray().length != 0) {
    queryBuilder.append(" detail.irmNumber in (");
    for (int i = 0; i < searchMasterDTO.getDetailIRMNumberArray().length; i++) {
    if (searchMasterDTO.getDetailIRMNumberArray().length == 1) {
    queryBuilder.append(" :IRMNO" + i);
    } else {
    queryBuilder.append(" :IRMNO" + i);
    if (searchMasterDTO.getDetailIRMNumberArray().length != i + 1) {
    queryBuilder.append(" , ");
    }
    }
    detailMap.put("IRMNO" + i, searchMasterDTO.getDetailIRMNumberArray()[i]);
    }
    queryBuilder.append(") and");
    }
    // if (!StringUtils.isBlank(searchMasterDTO.getRemittanceReferenceNumber())) {
    // query.append(" master.remittanceReferenceNumber= :REMITTANCEREFERENCENUMBER and ");
    // parameterizedMap.put("REMITTANCEREFERENCENUMBER", searchMasterDTO.getRemittanceReferenceNumber());
    // }
    if (!StringUtils.isBlank(searchMasterDTO.getSwiftOtherBankRefNumber())) {
    query.append(" master.swiftOtherBankRefNumber= :SWIFTOTHERBANKREF and ");
    parameterizedMap.put("SWIFTOTHERBANKREF", searchMasterDTO.getSwiftOtherBankRefNumber());
    }
    if (searchMasterDTO.getAdCodeId() != null && !StringUtils.isBlank(searchMasterDTO.getAdCodeId().getId())) {
    query.append(" ad.id=:ADCODEID and ");
    parameterizedMap.put("ADCODEID", searchMasterDTO.getAdCodeId().getId());
    }
    if (null != searchMasterDTO.getRemittanceCurrencyId() && !StringUtils.isBlank(searchMasterDTO.getRemittanceCurrencyId().getId())) {
    query.append(" master.remittanceCurrencyId.id=:CURRID and ");
    parameterizedMap.put("CURRID", searchMasterDTO.getRemittanceCurrencyId().getId());
    }
    if (!StringUtils.isBlank(searchMasterDTO.getIeCode())) {
    query.append(" master.ieCode=:IECODE and ");
    parameterizedMap.put("IECODE", searchMasterDTO.getIeCode());
    }
    // if (!StringUtils.isBlank(searchMasterDTO.getDetailIRMNumber())) {
    // queryBuilder.append(" detail.irmNumber=:IRMNO and ");
    // detailMap.put("IRMNO", searchMasterDTO.getDetailIRMNumber());
    // }
    if (!StringUtils.isBlank(searchMasterDTO.getStatus())) {
    if (!searchMasterDTO.getStatus().equals(IRMStatusEnum.CANCELED.getValue())) {
    query2.append(" master.status ='ACTIVE' ");
    query2.append(" and master.remittanceStatus =:REMITTANCESTATUS ");
    parameterizedMap.put("REMITTANCESTATUS", searchMasterDTO.getStatus());
    } else {
    query2.append(" master.remittanceStatus ='CANCELLED' ");
    }
    } else {
    parameterListMap.put("masterStatusList", Arrays.asList(masterStatusList));
    query2.append(" master.status in(:masterStatusList) ");
    }
    if (!searchMasterDTO.isSearchFlag()) {
    if (!SecurityConstants.BANK_USER.equalsIgnoreCase(userType)) {
    parameterListMap.put("ADMASTERIDLIST", Arrays.asList(adMasterList));
    query2.append(" and master.adCodeId.adCode in (:ADMASTERIDLIST) ");
    }
    }
    query2.append(" and master.flag!='D'");
    // query2.append("order by master.addedDate desc");

    if (StringUtils.isBlank(searchMasterDTO.getDetailIRMNumber())) {
    countQuery = populateQuery(countQueryStr + csb.toString() + query.toString() + query2.toString(), parameterizedMap, parameterListMap);
    resultCount = (Long) countQuery.uniqueResult();
    query2.append("order by master.addedDate desc");
    resultQuery = populateQuery(sb.toString() + query.toString() + query2.toString(), parameterizedMap, parameterListMap);
    if (!searchMasterDTO.isExportFlag()) {
    resultQuery.setFirstResult(searchMasterDTO.getFirstRow());
    resultQuery.setMaxResults(searchMasterDTO.getMaximumResultCount());
    }
    } else {
    parameterizedMap.putAll(detailMap);
    countQuery = populateQuery(countQueryStr + csb.toString() + query.toString() + queryBuilder.toString() + query2.toString(), parameterizedMap, parameterListMap);
    resultCount = (Long) countQuery.uniqueResult();
    query2.append("order by master.addedDate desc");
    resultQuery = populateQuery(sb.toString() + query.toString() + queryBuilder.toString() + query2.toString(), parameterizedMap, parameterListMap);
    if (!searchMasterDTO.isExportFlag()) {
    resultQuery.setFirstResult(searchMasterDTO.getFirstRow());
    resultQuery.setMaxResults(searchMasterDTO.getMaximumResultCount());
    }
    }

    resultList = resultQuery.list();
    SearchResultDTO searchResultDTO = new SearchResultDTO();
    searchResultDTO.setNumberOfRecordsFound(resultCount.intValue());
    searchResultDTO.setRemittanceTransactionMasterVOList((List) CollectionUtils.convertEntityObjectList(resultList, remittanceTransactionMasterVO));
    return searchResultDTO;

  2. disar says:

    Hi Pankaj,
    the method createQuery(…) is deprecated.
    Isn’t better use, instead of using Criteria, CriteriaBuilder?
    However you done a very good job, your tutorials is very helpful for me.
    Thanks

    1. Pankaj says:

      Hmm, I need to look at the current version and update these. Added to my todo list. Thanks for pointing it out.

  3. Nilesh Gattani says:

    “SELECT”
    DURM.USER_ID,
    DRM.RETURN_ID,
    DRM.RETURN_NAME,
    DBM.BANK_ID,
    DBM.BANK_NAME
    FROM DCP_USER_MASTER DUM
    LEFT JOIN
    DCP_USER_RIGHTS_MAPPER DURM
    ON DUM.USER_ID=DURM.USER_ID
    LEFT JOIN DCP_RETURN_MASTER DRM
    ON DURM.RETURN_ID=DRM.RETURN_ID
    LEFT JOIN DCP_BANK_MASTER DBM
    ON DURM.BANK_ID=DBM.BANK_ID
    WHERE
    DUM.USER_NAME = ?

    how to convert this query table data into hibernate using mapping many to many, kinldy suggest me

  4. Raju Sharma says:

    Hello Pankaj , i want to join three table , table a and b with many to one and table b and c with one to one mapping. Then i want to display table a data , so please mail the join and mapping details and criteria query for it .

  5. Sunil Kale says:

    SELECT d.level, s.slide_pk from slideimage s
    LEFT JOIN studyanimal a ON s.animal_fk=a.animal_pk
    LEFT JOIN study_dosage sd ON a.study_dos_fk=sd.study_dos_pk
    LEFT JOIN dosage d ON sd.dosage_fk=d.dosage_pk
    where s.study_fk=2
    order by d.level;

    Hi pankaj this is my query i want it using Hibernate..How to do this..Please help me i am stuck here

  6. Rutaveej Shah says:

    Hi panakj..
    I have some doubt regarding hibernate criteria query.In a one session if i am saving a data in one table and then fetching the data from the same table using criteria in same session then my data get inserted in database.If some exception is occurred then it doesn’t get rollback.Is there any solution for that.

  7. babaye says:

    Hello,

    Thank you for you tutorial.

    In this example :

    criteria.setFetchMode(“employee.address”, FetchMode.JOIN);
    criteria.createAlias(“employee.address”, “address”);

    The createAlias option for Join (Inner_Join by default) is overriding the FetchMode.JOIN (Outer Join ). Is is the same if you change the odrer (createAlias before FetchMode) ? Is there a documentation on that ?

  8. Trinath says:

    Hi Pankaj,
    Why Hibernate Converts Checked Exceptions to Un-checked Exceptions ? what is the reason behind it??Plzz tell me..

    Awaiting for Your Quick Response….
    Thanx for Your Time!!!!!!!!

    Regards
    Trinath

    1. Pankaj says:

      It’s more like a design decision, if you are using Hibernate as ORM tool and something goes wrong, there is no easy way you can catch exception and then recover from it. So hibernate doesn’t enforce you to catch all the exceptions and uses unchecked exceptions, something like NullPointerException.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages