Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Java Hibernate Cookbook
Java Hibernate Cookbook

Java Hibernate Cookbook: Over 50 recipes to help you build dynamic and powerful real-time Java Hibernate applications

Arrow left icon
Profile Icon Prajapati Profile Icon Ranapariya
Arrow right icon
€26.98 €29.99
eBook Sep 2015 250 pages 1st Edition
eBook
€26.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Prajapati Profile Icon Ranapariya
Arrow right icon
€26.98 €29.99
eBook Sep 2015 250 pages 1st Edition
eBook
€26.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€26.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Java Hibernate Cookbook

Chapter 2. Understanding the Fundamentals

In this chapter, we will cover the following recipes:

  • Building a SessionFactory
  • Creating a generic SessionFactory provider class
  • Opening a new session
  • Opening a stateless session
  • Saving an object to the database
  • Fetching an object from the database
  • Removing an object from the database
  • Updating an object
  • Creating a criteria
  • Restricting the results using a criteria
  • Pagination using a criteria
  • Sorting the results
  • Transforming a result
  • Using basic projection

Introduction

Before we proceed, it's necessary to learn about the fundamentals of hibernate: the classes and interfaces required.

In this chapter, we will cover the fundamentals of hibernate, such as SessionFactory, Session, and Criteria. We will discuss the importance of SessionFactory in the hibernate application. Criteria is used to do the actual transaction or the CRUD (Create, Read, Update, Delete) operation. Apart from this, we will cover some basic and useful functionalities, such as the sorting of results, limiting the number of rows, transforming a result, and the basics of projections.

Building a SessionFactory

First, we will discuss SessionFactory and how to create it in detail. As the name suggests, a SessionFactory is a factory of sessions.

A SessionFactory has the following features:

  • It's an interface implemented using the singleton pattern.
  • It's created using the configuration provided by the configuration file.
  • It's thread-safe, so it's created once during the application's lifetime, and multiple users or threads can access it at the same time without any concurrency issue.
  • As a SessionFactory object is immutable, changes made to the configuration will not affect the existing factory object.
  • It's a factory class, and its main duty is to create, manage, and retrieve a session on request. A Session is used to get a physical connectivity with the database.

How to do it…

If you are using a version of hibernate that is earlier than 4, use the following code to create a SessionFactory:

/* Line 1 */ Configuration cfg = new Configuration();
...

Creating a generic SessionFactory provider class

Now, we will create a helper class, which will help us to set and get SessionFactory on demand.

We require SessionFactory at every point while working with hibernate. So, we will create a HibernateUtil.java class.

Tip

This is just a naming convention and not a hibernate standard but is used globally by developers and communities for the ease of use.

How to do it…

Here, we will create a Java file with the name HibernateUtil.java:

  1. Enter the following code in the HibernateUtil.java file:
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    public class HibernateUtil {
      private static final SessionFactory sessionFactory;
        
      static {
        try {
          // Create the SessionFactory from hibernate.cfg.xml
         sessionFactory = new Configuration().configure().buildSessionFactory();
    
          // Use code below for Hibernate version 4
          // Configuration configuration = new Configuration();
          // configuration = configuration...

Opening a new session

A Session is also known as an interface that is used to get a physical connectivity with a database. It is instantiated every time we need to interact with the database for the CRUD (Create, Read, Update, Delete) operations. Persistent objects always travel from the application to the database and vice versa only through the Session.

Now, let's find out more about Session and how to open a new Session using a SessionFactory.

Getting ready

Before we create a Session object, we need to get an object such as a SessionFactory as a prerequisite:

  1. Use the following code to open a new session:
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

How to do it…

Now, we will open a new Session with the database:

Session session = sessionFactory.openSession();

Other methods are also available to open a Session, as shown in the following code:

Session openSession(org.hibernate.Interceptor interceptor);
Session openSession(java.sql.Connection connection, org.hibernate...

Opening a stateless session

Basically, a stateless session is used to perform only one task. It does not take place in any type of cache. A cache is used to store the frequently used objects in the current context. There are some cases where a stateless session is very useful; for example, if we are reading data from a file and inserting it into the database, we don't need to cache that data further because this is a one-time operation.

Apart from this, a stateless session does not use dirty checking while performing a transactional operation. The collections, as well as hibernate's event model and interceptors, are ignored by a stateless session.

How to do it…

Now, let's look at how to create a stateless session. It's the same as creating a session, but the method is different:

  1. Enter the following code to open a stateless session:
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openStatelessSession();

Saving an object to the database

Now, we have reached a point from where we start the actual transactional operations, such as insert, delete, update, and so on.

In this recipe, we will look at how to save an object to the database.

The equivalent SQL query is as follows:

  • Department: INSERT INTO department (deptName) VALUES ('department name');
  • Employee: INSERT INTO employee (firstName, salary, department) VALUES ('first name', salary value, department id);

How to do it…

Let's look at how to save an object to the database:

  1. The following code shows how we can save an object to the database:
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();
    
    // begin a transaction 
    session.getTransaction().begin(); 
    
    //creating a department object
    Department department = new Department();
    department.setDeptName("developement");
    
    // save department object
    session.save(department); 
    System.out.println("Department...

Introduction


Before we proceed, it's necessary to learn about the fundamentals of hibernate: the classes and interfaces required.

In this chapter, we will cover the fundamentals of hibernate, such as SessionFactory, Session, and Criteria. We will discuss the importance of SessionFactory in the hibernate application. Criteria is used to do the actual transaction or the CRUD (Create, Read, Update, Delete) operation. Apart from this, we will cover some basic and useful functionalities, such as the sorting of results, limiting the number of rows, transforming a result, and the basics of projections.

Building a SessionFactory


First, we will discuss SessionFactory and how to create it in detail. As the name suggests, a SessionFactory is a factory of sessions.

A SessionFactory has the following features:

  • It's an interface implemented using the singleton pattern.

  • It's created using the configuration provided by the configuration file.

  • It's thread-safe, so it's created once during the application's lifetime, and multiple users or threads can access it at the same time without any concurrency issue.

  • As a SessionFactory object is immutable, changes made to the configuration will not affect the existing factory object.

  • It's a factory class, and its main duty is to create, manage, and retrieve a session on request. A Session is used to get a physical connectivity with the database.

How to do it…

If you are using a version of hibernate that is earlier than 4, use the following code to create a SessionFactory:

/* Line 1 */ Configuration cfg = new Configuration();
/* Line 2 */ cfg = cfg.configure();
/*...

Creating a generic SessionFactory provider class


Now, we will create a helper class, which will help us to set and get SessionFactory on demand.

We require SessionFactory at every point while working with hibernate. So, we will create a HibernateUtil.java class.

Tip

This is just a naming convention and not a hibernate standard but is used globally by developers and communities for the ease of use.

How to do it…

Here, we will create a Java file with the name HibernateUtil.java:

  1. Enter the following code in the HibernateUtil.java file:

    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    public class HibernateUtil {
      private static final SessionFactory sessionFactory;
        
      static {
        try {
          // Create the SessionFactory from hibernate.cfg.xml
         sessionFactory = new Configuration().configure().buildSessionFactory();
    
          // Use code below for Hibernate version 4
          // Configuration configuration = new Configuration();
          // configuration = configuration...

Opening a new session


A Session is also known as an interface that is used to get a physical connectivity with a database. It is instantiated every time we need to interact with the database for the CRUD (Create, Read, Update, Delete) operations. Persistent objects always travel from the application to the database and vice versa only through the Session.

Now, let's find out more about Session and how to open a new Session using a SessionFactory.

Getting ready

Before we create a Session object, we need to get an object such as a SessionFactory as a prerequisite:

  1. Use the following code to open a new session:

    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

How to do it…

Now, we will open a new Session with the database:

Session session = sessionFactory.openSession();

Other methods are also available to open a Session, as shown in the following code:

Session openSession(org.hibernate.Interceptor interceptor);
Session openSession(java.sql.Connection connection, org.hibernate.Interceptor...

Opening a stateless session


Basically, a stateless session is used to perform only one task. It does not take place in any type of cache. A cache is used to store the frequently used objects in the current context. There are some cases where a stateless session is very useful; for example, if we are reading data from a file and inserting it into the database, we don't need to cache that data further because this is a one-time operation.

Apart from this, a stateless session does not use dirty checking while performing a transactional operation. The collections, as well as hibernate's event model and interceptors, are ignored by a stateless session.

How to do it…

Now, let's look at how to create a stateless session. It's the same as creating a session, but the method is different:

  1. Enter the following code to open a stateless session:

    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openStatelessSession();

Saving an object to the database


Now, we have reached a point from where we start the actual transactional operations, such as insert, delete, update, and so on.

In this recipe, we will look at how to save an object to the database.

The equivalent SQL query is as follows:

  • Department: INSERT INTO department (deptName) VALUES ('department name');

  • Employee: INSERT INTO employee (firstName, salary, department) VALUES ('first name', salary value, department id);

How to do it…

Let's look at how to save an object to the database:

  1. The following code shows how we can save an object to the database:

    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();
    
    // begin a transaction 
    session.getTransaction().begin(); 
    
    //creating a department object
    Department department = new Department();
    department.setDeptName("developement");
    
    // save department object
    session.save(department); 
    System.out.println("Department saved, id:  " + department.getId()...

Fetching an object from the database


Now we will take a look at how to fetch objects using a Session. Here, we will also see how to get only one record using the primary key column. We override a toString() method in the Employee and Department classes so that it's easy to display the data within an object, as shown in the following code:

@Override
    public String toString() {
      return "\nEmployee"
      + "\n id: " + this.getId()
      + "\n first name: " + this.getFirstName()
      + "\n salary: " + this.getSalary()
      + "\n department: " + this.getDepartment().getDeptName();
    }

How to do it…

Here, we are trying to get an employee having id equals 1.

The equivalent SQL query is as follows:

SELECT * FROM employee WHERE id=1;

Now, let's look at how to do the same using hibernate:

  1. Enter the following code to fetch an object of the employee type, where the id is 1:

    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session =  sessionFactory.openSession();
    Employee...

Removing an object from the database


Now, we take a look at how to remove a record from the database.

How to do it…

Here, we are trying to remove an employee object having id equals 1.

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

DELETE FROM employee WHERE id=1;

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

Code

Enter the following code to delete an object of the employee type, where id is 1:

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();

session.getTransaction().begin();
Employee employee = (Employee) session.get(Employee.class, new Long(1));
session.delete(employee);
session.getTransaction().commit();

session.close(); 
HibernateUtil.shutdown();

Output

The output will be as follows:

Hibernate: select employee0_.id as id0_1_, employee0_.department as department0_1_, employee0_.firstName as firstName0_1_, employee0_.salary as salary0_1_, department1_.id as id1_0_, department1_.deptName as deptName1_0_...

Updating an object


Here, we look at how to get a record from the database and update the same record to the database. The main goal is to get Employee#2 and update the first name, aarush, to aarush_updated.

How to do it…

Here, we are trying to update an employee object having id equals 2.

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

UPDATE employee SET firstName='aarush_updated' WHERE id=2;

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

Code

Enter the following code to update an object of the employee type, where id is 2:

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();

/* Line 3 */ Employee employee = (Employee) session.get(Employee.class, new Long(2));

System.out.println("\nOld Employee...");
System.out.println(employee.toString());

session.getTransaction().begin();
/* Line 9 */ employee.setFirstName("aarush_updated");
/* Line 10 */ session.update(employee);
session.getTransaction().commit...
Left arrow icon Right arrow icon

Key benefits

  • Learn to associate JDBC and Hibernate with object persistence
  • Manage association mappings, implement basic annotations and learn caching
  • Get to grips with Hibernate fundamentals from installation to developing a business application with this step-by-step guide

Description

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.

Who is this book for?

This is book for Java developers who now want to learn Hibernate. Good knowledge and understanding of Java is preferred to allow efficient programming of the core elements and applications; it would be helpful if readers are familiar with the basics of SQL.

What you will learn

  • Set up and install Hibernate on your system and explore different ways in which Hibernate can be configured
  • Learn the basic concepts and fundamentals of Java Hibernate
  • Define mappings without a use of XML file using Annotations
  • Persist collection elements such as list, map, set and array
  • Explore the various mapping options and learn to work with Hibernate associations
  • Understand advanced Hibernate concepts such as caching and inheritance
  • Develop an engaging and robust real-world hibernate application based on a common business scenario
  • Integrate Hibernate with other frameworks to develop robust enterprise applications

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 18, 2015
Length: 250 pages
Edition : 1st
Language : English
ISBN-13 : 9781784398408
Vendor :
Oracle
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Sep 18, 2015
Length: 250 pages
Edition : 1st
Language : English
ISBN-13 : 9781784398408
Vendor :
Oracle
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 103.97
Java Hibernate Cookbook
€36.99
Test-Driven Java Development
€41.99
Mastering Hibernate
€24.99
Total 103.97 Stars icon

Table of Contents

9 Chapters
1. Setting Up Hibernate Chevron down icon Chevron up icon
2. Understanding the Fundamentals Chevron down icon Chevron up icon
3. Basic Annotations Chevron down icon Chevron up icon
4. Working with Collections Chevron down icon Chevron up icon
5. Working with Associations Chevron down icon Chevron up icon
6. Querying Chevron down icon Chevron up icon
7. Advanced Concepts Chevron down icon Chevron up icon
8. Integration with Other Frameworks Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.