MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to work with Comparator Methods in Hibernate Criteria Query (HCQ)

This article will discuss about some methods which will help you to extract result which are based on comparison of a field.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Introduction

We will discuss different criteria which can be added to make a successful query in different conditions.

Let’s discuss simple examples to start understanding this.

First we assume that following are records in the contact table:

Records in the contact table

Figure 1: Records in the contact table

We make a class Course and we will perform operation on this class using the Hibernate Criteria Query.

Listing 1: Course class

package model;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 *
 * @author Anurag
 */
@Entity
public class Course implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "C_ID")
    private Long id;
    private String name;
    private int duration;

    public Course() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Course(String n, int dur) {
        name = n;
        duration = dur;
    }

    public int getDuration() {
        return duration;
    }

    public void setDuration(int duration) {
        this.duration = duration;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
 
  • We defined a class Course with fields like id, name, duration.
  • We define the setter and getter function for these
  • We set the id to be auto generated and also we set the name for this column to be C_ID

Now we will define the configuration file:

Listing 2: 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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernateArt</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">csanurag</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <mapping class="model.Course"/>
    </session-factory>
</hibernate-configuration>
 
  • We defined the configuration parameter for the database
  • We also defined the mapping class which in this case is class Course.

Now we define the Utility class which will be used to obtain instance of session factory

Listing 3: Utility class

package Main;

/**
 *
 * @author Anurag
 */
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class Utility {

    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {

            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
  • We made a sessionFactory object.
  • We initialized this within a static block so that sessionFactory get initialized whenever an object of this class is made.
  • We made a getter to obtain the sessionFactory object.

Now we make the main class which will use the hibernate criteria query.

Listing4: App2 class (le method)

package Main;
	
/**
 *
 * @author Anurag
 */
import java.util.Iterator;
import java.util.List;
import model.Course;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;

public class App2 {

    public static void main(String args[]) {

        SessionFactory sf = Utility.getSessionFactory();
        Session s = sf.getCurrentSession();

        Transaction tx = s.beginTransaction();
        Criteria crit = s.createCriteria(Course.class);
        crit.add(Expression.le("duration", 6));
        List course = crit.list();
        for (Iterator it = course.iterator(); it.hasNext();) {
            Course c = (Course) it.next();
            System.out.println("ID: " + c.getId());
            System.out.println("Name: " + c.getName());
            System.out.println("Duration: " + c.getDuration());
        }
        tx.commit();
    }
}
  • le method take 2 argument which is (field name,value)
  • We make criteria for the field duration
  • We select all those records in which the duration is less than or equal to 6

Output

Figure 2: Output

Listing 5: App2 class (lt method)

package Main;

/**
 *
 * @author Anurag
 */
import java.util.Iterator;
import java.util.List;
import model.Course;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;

public class App2 {

    public static void main(String args[]) {

        SessionFactory sf = Utility.getSessionFactory();
        Session s = sf.getCurrentSession();

        Transaction tx = s.beginTransaction();
        Criteria crit = s.createCriteria(Course.class);
        crit.add(Expression.lt("id",2));
        List course = crit.list();
        for (Iterator it = course.iterator(); it.hasNext();) {
            Course c = (Course) it.next();
            System.out.println("ID: " + c.getId());
            System.out.println("Name: " + c.getName());
            System.out.println("Duration: " + c.getDuration());
        }
        tx.commit();
    }
}
  • lt method take 2 argument which is (field name,value)
  • We make criteria for the field id
  • We select all those records in which the id is less than 2

Output App2 class (lt method)

Figure 3: Output App2 class (lt method)

Listing 6: App2 class (gt method)

package Main;

/**
 *
 * @author Anurag
 */
import java.util.Iterator;
import java.util.List;
import model.Course;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;

public class App2 {

    public static void main(String args[]) {

        SessionFactory sf = Utility.getSessionFactory();
        Session s = sf.getCurrentSession();

        Transaction tx = s.beginTransaction();
        Criteria crit = s.createCriteria(Course.class);
        crit.add(Expression.gt("duration", 6));
        List course = crit.list();
        for (Iterator it = course.iterator(); it.hasNext();) {
            Course c = (Course) it.next();
            System.out.println("ID: " + c.getId());
            System.out.println("Name: " + c.getName());
            System.out.println("Duration: " + c.getDuration());
        }
        tx.commit();
    }
}
  • gt method take 2 argument which is (field name,value)
  • We make criteria for the field duration
  • We select all those records in which the duration is greater than 6

App2 class (gt method)

Figure 4: App2 class (gt method)

Listing 7: App2 class (ge method)

package Main;

/**
 *
 * @author Anurag
 */
import java.util.Iterator;
import java.util.List;
import model.Course;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;

public class App2 {

    public static void main(String args[]) {

        SessionFactory sf = Utility.getSessionFactory();
        Session s = sf.getCurrentSession();

        Transaction tx = s.beginTransaction();
        Criteria crit = s.createCriteria(Course.class);
        crit.add(Expression.ge("duration", 6));
        List course = crit.list();
        for (Iterator it = course.iterator(); it.hasNext();) {
            Course c = (Course) it.next();
            System.out.println("ID: " + c.getId());
            System.out.println("Name: " + c.getName());
            System.out.println("Duration: " + c.getDuration());
        }
        tx.commit();
    }
}
  • gt method take 2 argument which is (field name,value)
  • We make criteria for the field duration
  • We select all those records in which the duration is greater than or equal to 6

App2 class (ge method)

Figure 5: App2 class (ge method)

This is all for today’s article. We will discuss more methods in next coming articles. See you next time.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?

Did you like the post?

Help us to keep publishing good contents like this.

SUPPORT US

funded

remaining

[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login