Book Image

Mastering Hibernate

Book Image

Mastering Hibernate

Overview of this book

Hibernate has been so successful since its inception that it even influenced the Java Enterprise Edition specification in that the Java Persistence API was dramatically changed to do it the Hibernate way. Hibernate is the tool that solves the complex problem of Object Relational Mapping. It can be used in both Java Enterprise applications as well as .Net applications. Additionally, it can be used for both SQL and NoSQL data stores. Some developers learn the basics of Hibernate and hit the ground quickly. But when demands go beyond the basics, they take a reactive approach instead of learning the fundamentals and core concepts. However, the secret to success for any good developer is knowing and understanding the tools at your disposal. It’s time to learn about your tool to use it better This book first explores the internals of Hibernate by discussing what occurs inside a Hibernate session and how Entities are managed. Then, we cover core topics such as mapping, querying, caching, and we demonstrate how to use a wide range of very useful annotations. Additionally, you will learn how to create event listeners or interceptors utilizing the improved architecture in the latest version of Hibernate.
Table of Contents (16 chapters)


Object-Relational Mapping is a difficult problem, and the Hibernate team has solved that problem for us. Some developers have a love-hate relationship with Hibernate because it has made life easier for many developers, but at times, unexpected behavior is encountered and it quickly becomes a mystery. This book was written to uncover these mysteries. It does so by looking under the hood; it first discusses the internals of Hibernate, and later it covers advanced topics on mapping techniques, annotations, fetching, caching, and versioning. It also addresses other topics that are of interest to technical leads and software architects, such as statistics and metrics, concurrency, and transaction management.

Although, it is recommended that you read this book in its entirety, the topics are carefully outlined so that it can also be used as a reference if you wish to learn about a specific feature.

What this book covers

Chapter 1, Entity and Session, covers the internal working of a session and how Hibernate manages entities inside a session. We will also explore the entity life cycle and discuss other topics related to sessions and entities such as stateless sessions, design patterns such as session-per-request, session-per-conversation, batch processing, and proxy objects.

Chapter 2, Advanced Mapping, talks about fundamental mapping concepts and how Hibernate bridges the gap between the object-oriented world and relational database. You will further read discussions on inheritance, and in-memory and in-database value generation. Moreover, the creation of custom mapped data types is also covered. This chapter also demonstrates how to work with collections and offers tips and tricks, and outlines the pitfalls when working with collections. Additionally, it covers batch updates and deletes. Finally, this chapter shows you how to implement object-oriented topics such as inheritance and polymorphism and map them correctly to a relational database.

Chapter 3, Working with Annotations, demonstrates the use of annotations and why and when to use them. Besides the common annotations, it highlights some rare ones, which can be quite useful for most developers. In addition to the common JPA annotations, this chapter also discusses some annotations that are only available in Hibernate.

Chapter 4, Advanced Fetching, shows various fetching strategies and discusses the use of Hibernate and native query languages, criteria objects, filters, and other topics related to data fetch.

Chapter 5, Hibernate Cache, covers various cache structures such as first-level and second-level. Additionally, it explores various cache strategies and how to collect statistics related to caching.

Chapter 6, Events, Interceptors, and Envers, covers events and interceptors in Hibernate and how you can use them to implement a functionality similar to DB triggers and other event-based functions. Furthermore, it covers Entity Auditing (Envers); which implements entity revision management to automatically store historical snapshots of entities and also provides an auditing mechanism.

Chapter 7, Metrics and Statistics, demonstrates how to generate and collect metrics and statistical data within Hibernate. This includes entity, query, collection, and cache statistics. It further shows how to access this data via JMX, that is, Java Management Extensions.

Chapter 8, Addressing Architecture, shows how architectural concerns and constraints are addressed in Hibernate, which includes concurrency and transaction management, scalability, and performance.

Chapter 9, EJB and Spring Context, shows how to correctly create and deploy your application in two popular Java contexts, EJB and Spring.

What you need for this book

All the code in this book is written using Java SE 7. You will need a Java IDE (Integrated Development Environment) such as Eclipse, Netbeans, or IntelliJ. Additionally, you will need a relational database, such as Oracle, DB2, MySQL, or PostgreSQL. The database used to create the examples in this book is PostgreSQL database (version 9.3).

Most of the examples in the initial chapters are single-threaded Java applications that do not need to run inside a Java Enterprise container or Spring. However, in later chapters, you will need to test your enterprise application in a container. In this case, JBoss (AS 7) or Spring (version 4.2) were chosen.

Although, you may not need it, it is highly recommended that you use a dependency manager for your work. The examples in this book use Apache Maven, version 3.

Who this book is for

This book covers fundamental concepts of Hibernate. It is intended for highly technical developers who wish to understand the internals of Hibernate. This book can also be used by developers who have already started using Hibernate and wish to get better at it. It is not intended to make you a Java or SQL developer. If you wish to learn about the how and why, then this book is for you. Mastery is about details.


In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The @Any and @ManyToAny annotations are only available in Hibernate."

A block of code is set as follows:

public class Person {
private long id;
private String firstname;
private String lastname;
private String ssn;
private Date birthdate;
// getters and setters

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

public class Circle {

Any command-line input or output is written as follows:

select as id1_0_0_,
course0_.title as title2_0_0_,
students1_.course_id as course_i4_0_1_, as id1_1_1_,
students1_.gender as gender2_1_2_, as name3_1_2_ 
Course course0_


Warnings or important notes appear in a box like this.


Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.

  2. Hover the mouse pointer on the SUPPORT tab at the top.

  3. Click on Code Downloads & Errata.

  4. Enter the name of the book in the Search box.

  5. Select the book for which you're looking to download the code files.

  6. Choose from the drop-down menu where you purchased this book from.

  7. Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows

  • Zipeg / iZip / UnRarX for Mac

  • 7-Zip / PeaZip for Linux


Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to and enter the name of the book in the search field. The required information will appear under the Errata section.


Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.


If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.