Creating a criteria

Generally, we require filtered data in a SQL query, in which we use the WHERE clause to apply a condition to the data. Apart from the WHERE clause, we can use ORDER BY to apply sorting to the data, either ascending or descending, and LIMIT (if it's MySQL) to get a limited number of rows.

Hibernate allows us to perform all the operations mentioned before in an object-oriented way. A criteria is an interface; it provides an API to perform WHERE, ORDER BY, LIMIT, result transformation, and so on.

How to do it...

Here, we will try to create a criteria for employee.

The SQL query executed to achieve the same result is as follows:

SELECT * FROM employee;

Now, let's take a look at how to do the same using hibernate.

Code

Enter the following code to create a criteria for employee:

Criteria criteria = session.createCriteria(Employee.class);
List<Employee> employees = criteria.list();
for(Employee employee : employees){
System.out.println(employee.toString());
}

Output

The output will be as follows:

Hibernate: select this_.id as id0_1_, this_.department as department0_1_, this_.firstName as firstName0_1_, this_.salary as salary0_1_, department2_.id as id1_0_, department2_.deptName as deptName1_0_ from employee this_ left outer join department department2_ on this_.department=department2_.id

Employee
 id: 1
 first name: yogesh
 salary: 50000.0
 department: developement

Employee
 id: 2
 first name: aarush_updated
 salary: 35000.0
 department: developement

How it works…

Here, we created a criteria for the Employee class, and using it, we tried to load all the records from the Employee table. Previously, we used session.load() or session.get() to fetch the record from the database, but these methods return only one record at a time. Now, we can fetch multiple records using criteria().

The criteria.list() method returns java.util.List<Object>. In our example it returns java.util.List<Employee> because we created a criteria using the Employee class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.19.243