Newsletter

Hibernate Criteria, Adding Conditions To Criteria

Hibernate » on Jul 13, 2011 { 8 Comments } By Sivateja

If we want to add some sorting order for the objects, before the objects are going to store in list object then we need to add an Order class object to the Criteria class object by calling addOrder() method..,

  • Order is a class given in “org.hibernate.Criterion” package
  • In Order class, we have 2 static methods, asc()[ascending order] and dsc()[descending order] for getting an objects in required order
  • Internal concept is, hibernate will select the records (rows) from PRODUCT table and stores them into a ResultSet and then converts each row data of resultset into a POJO class object basing on our field type, then all these objects into a list according to the order you have given

Let’s see an example..

required file…

  • Product.java(POJO class)
  • Product.hbm.xml
  • hibernate.cfg.xml
  • ForOurLogic.java (For writing our business logic)

Product.java

package str;

public class Product{

	private int productId;
	private String proName;
	private double price;

	public void setProductId(int productId)
	{
	    this.productId = productId;
	}
	public int getProductId()
	{
	    return productId;
	}

	public void setProName(String proName)
	{
	    this.proName = proName;
	}
	public String getProName()
	{
	    return proName;
	}

	public void setPrice(double price)
	{
	    this.price = price;
	}
	public double getPrice()
	{
	    return price;
	}
}

Product.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="str.Product" table="products">

<id name="productId" column="pid"  />
<property name="proName" column="pname" length="10"/>
<property name="price"/>

    </class>
</hibernate-mapping>

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>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>

<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>

<mapping resource="Product.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>

ForOurLogic.java

package str;

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.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

public class ForOurLogic { 

	@SuppressWarnings("unchecked")
	public static void main(String[] args)
	{

		Configuration cfg = new Configuration();
		cfg.configure("hibernate.cfg.xml"); 

		SessionFactory factory = cfg.buildSessionFactory();
		Session session = factory.openSession();

		Criteria crit = session.createCriteria(Product.class);
		Criterion cn = Restrictions.gt("price",new Double(17000));
		crit.add(cn);
		crit.addOrder(Order.asc("price"));
		List l=crit.list();
		System.out.println("List total size..._"+l.size());
		Iterator it=l.iterator();

		while(it.hasNext())
		{
			Product p=(Product)it.next();
			System.out.println(p.getProductId());
			//System.out.println(p.getProName());
			//System.out.println(p.getPrice());
		}

		session.close();
		factory.close();
	}

}

Note:

  • In line number 27, used Restrictions to get the price greater then 17000, and remember here price is the pojo class variable
  • In line number 28, added criterion objects to criteria object
  • line number 29 its our current program concept,  we are calling addOrder() method to get the price in assenting order
  • We can use for proName also, its depends on your requirement

 

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

8 Responses to “Hibernate Criteria, Adding Conditions To Criteria”
  1. Anand says:

    This tutorial is very very good….it is really very very helpful from understanding java tech…many many thanxxx to you Sir…

  2. Java4s says:

    @Anand

    Glad to hear that it helped you much :-), thanks for your feedback.

  3. hi sir, in hibernate application when i got offline then this error occur ,why?….log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
    log4j:WARN Please initialize the log4j system properly.
    Exception in thread “main” org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1491)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
    at com.action.ForOurLogic.main(ForOurLogic.java:22)
    Caused by: org.dom4j.DocumentException: hibernate.sourceforge.net Nested exception: hibernate.sourceforge.net
    at org.dom4j.io.SAXReader.read(SAXReader.java:484)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1481)
    … 2 more

    ,sir huge thanks for supporting us and always be…………..

  4. avneesh says:

    Before some time I was new to java and hibernate. But this link guide me step by step. so now I am comfortable with these things.
    Its very useful for fresher.
    Thanks a lot sir for this tutorial

  5. karthick says:

    very use full to me….could u please explain this concept in multiple condition scenario….thanx in advance…

  6. karthick says:

    could u please tell me what are all methods available in Restriction interface…thanx in advance…

  7. john says:

    HI can you explain this Product p=(Product)it.next(); not able to understand object type casting why i need to do this

  8. naresh says:

    normally it.next() returns object type to convert into product type we need to type cast it

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.