Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

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

×

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 Projection in Hibernate Criteria Query (HCQ)

In this article we will discuss about making use of projections in Hibernate Criteria Query (HCQ).

Introduction

In earlier tutorials, we learned how to use Hibernate Criteria Query. We obtained an object which contains all the field from table and we printed the values simply using iterator. Now, the problem arises if we want that the object loads only two fields from database instead of all fields. Here we can make use of Hibernate Projections. It can be applied to Criteria Query and can result in an object loaded with only those fields which you need ie. can load partial objects.

There are 2 main things to remember:

  • Projection is an Interface given in “org.hibernate.criterion” package
  • Projections is the class responsible for producing Projection objects.It has all static methods

Let’s discuss simple examples to start understanding this.

Below are the records which are within this table.

Database records

Figure 1: Database records

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;
    private int rating;

    public Course() {
    }

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

    public Long getId() {
        return id;
    }

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

    public int getRating() {
        return rating;
    }

    public void setRating(int rating) {
        this.rating = rating;
    }

    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,rating.
  • 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 for both the classes.

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;
    }
}

Lastly we make a class which will make this all work.

Listing 4: App2 class

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;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;

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);
        ProjectionList proList = Projections.projectionList();
        proList.add(Projections.property("name"));
        proList.add(Projections.property("rating"));
        crit.setProjection(proList);

        List course = crit.list();
        for (Iterator it = course.iterator(); it.hasNext();) {
            Object[] row = (Object[]) it.next();

            for (int i = 0; i < row.length; i++) {
                System.out.println(row[i]);
            }

        }
        tx.commit();
    }
}
  • Firstly, We made a session instance with help of session factory object.
  • Now we start the transaction.
  • We make a Criteria object for Course class object .
  • We select those fields which we want to display inside projection object.
  • The projection is passed to Criteria object.
  • We iterate through the list to obtain the resulting array and then show the resulting values though this array.
  • We commit the transaction to complete this transaction.
  • Output of the above program when ran will be :
    • J2EE
    • 5
    • Hibernate
    • 6
    • Spring
    • 8

Now, we will discuss some functions:

Listing 5: rowCount

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;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;

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.setProjection(Projections.rowCount());
        List course = crit.list();
        System.out.println(course);
        tx.commit();
    }
}
  • Firstly, We made a session instance with help of session factory object.
  • Now we start the transaction
  • We make a Criteria object for Course class object
  • The projection is passed to Criteria object. We make use of rowcount method
  • We commit the transaction to complete this transaction

The output for this program will be 3:

Listing 6: countDistinct

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;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;

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.setProjection(Projections.distinct(Projections.countDistinct("rating")));
        List course = crit.list();
        System.out.println("Distinct Count:  "+ course);
        tx.commit();
    }
} 
  • Firstly, We made a session instance with help of session factory object.
  • Now we start the transaction
  • We make a Criteria object for Course class object
  • The projection is passed to Criteria object. We make use of countDistinct method
  • We commit the transaction to complete this transaction

The output for this program will be 3:

We will discuss some more methods in next coming articles. Hope you enjoyed this article. 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?
Services
[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