Book Image

Java Hibernate Cookbook

Book Image

Java Hibernate Cookbook

Overview of this book

This book will provide a useful hands-on guide to Hibernate to accomplish the development of a real-time Hibernate application. We will start with the basics of Hibernate, which include setting up Hibernate – the pre-requisites and multiple ways of configuring Hibernate using Java. We will then dive deep into the fundamentals of Hibernate such as SessionFactory, session, criteria, working with objects and criteria. This will help a developer have a better understanding of how Hibernate works and what needs to be done to run a Hibernate application. Moving on, we will learn how to work with annotations, associations and collections. In the final chapters, we will see explore querying, advanced Hibernate concepts and integration with other frameworks.
Table of Contents (15 chapters)
Java Hibernate Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Restricting the results using a criteria


Let's take a look at how to add restrictions, which are equal to the WHERE clause in SQL.

How to do it…

Let's consider that we have four records in the employee table, as shown in the following tables:

This is the Employee table:

department

salary

firstName

id

1

50000

Yogesh

1

1

35000

Aarush

2

3

30000

Varsha

2

2

75000

Vishal

4

This is the Department table:

deptName

id

development

1

R&D

2

UI/UX

3

Now, the scenario is that we want to get only those employees whose salary is greater than 35000.

The equivalent SQL query to select the above employees is as follows:

SELECT * FROM employee WHERE salary > 35000;

Now, let's 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);
criteria.add(Restrictions.gt("salary", 35000));
List<Employee> employees = criteria.list();
for...