Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Mastering Hibernate
Mastering Hibernate

Mastering Hibernate: Learn how to correctly utilize the most popular Object-Relational Mapping tool for your Enterprise application

eBook
€8.99 €19.99
Paperback
€24.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

Mastering Hibernate

Chapter 2. Advanced Mapping

In this chapter, we will explore mapping concepts. This is at the core of the Object-Relational Mapping challenge to correctly map Java objects and classes to their persistence representation. As discussed in the previous chapter, the object-oriented world has a lot in common with the relational world, attributes, types, and so on. The ORM solutions, such as Hibernate, were created to address their notable differences, inheritance, composition, object reference and identification, and much more. After reading this chapter, you will be able to correctly map database identification to a class attribute using primitive data types or a more complex Java class. You will also see how to create associations between objects and annotate them correctly so that Hibernate has enough information about the relationships between table data. Furthermore, you will be able to instruct Hibernate to perform cascaded operations and map classes as part of an inheritance...

Mapping concepts

Mapping objects to relations is the core mission of Hibernate, and as we discussed previously, this can be a difficult challenge that can only be overcome by understanding the fundamental concepts.

Let's explore mapping concepts by reviewing some of the fundamentals of relational databases, such as relational algebra, simple and composite IDs, join tables, and foreign keys.

Instances and rows

The origin of relational database concepts is Relational Algebra, which is based on Set Theory. Just as we think of objects as instances of classes, you should also think of a database row (a tuple) as an element of a set (the relation) that is defined by the database tab.

For example, if your object graph contains an instance of the Person entity class that represents John and another instance that represents Sara, you should think of these as two rows in the Person table.

In both cases, by being an instance of a class or a row of a table, they agree to possess certain attributes...

Association cardinality

Just as relational databases define the cardinality of table relationships, ORM solutions also define the cardinality of entity associations. Before we discuss how to map associations, let's review how associations are created in a relational database. The following are the two types of relationship:

  • Foreign key relationship: You can relate a table to another by declaring a column as a foreign key of the other table. This is typically used for a 1:1 (one-to-one) or a M:1 (many-to-one) relationship. If you make the foreign key column UNIQUE, then you are defining a 1:1 relationship; otherwise, this is M:1. If you make it NULLABLE, then the relationship is optional; that is, 1:0, 1:1, M:0, or M:1.
  • Join table relationship: Another way to relate two tables is by creating a join table that will have at least two columns that store the primary keys of the rows that should be related. This is typically used for 1:M and M:N relationships. Both columns should be NON-NULLABLE...

Cascade operations

You may already be familiar with cascade delete and update in a relational database. In the ORM world, this notion is a little more complicated. Hibernate treats this as a transitive property that may or may not propagate to the associated entities, depending on the state of the objects (transient, detached, or persistent) as well as the cascade settings that you choose when you define your association.

Hibernate doesn't automatically propagate the persistence operations to the associated entities. However, you can control this behavior using the cascade attribute of an association.

JPA defines certain cascade types: ALL, DETACH, MERGE, PERSIST, REFRESH, and REMOVE. These correspond directly with the operations provided by the EntityManager interface.

The Hibernate Session interface provides additional operations, such as save, update, or replicate (some names are different in Hibernate and JPA but the underlying operations are the same; for example, detach versus evict...

Inheritance

One of the biggest challenges in mapping objects to relations is inheritance. Relational databases do not support this concept. So, ORM solutions need to get creative when dealing with this issue. JPA specifies several strategies, all of which are implemented by Hibernate and these will be discussed here.

Single table strategy

The default strategy to support class hierarchy, in the case of inheritance, is single table strategy. If you don't specify any strategy, Hibernate will look for (or create) a single table with the name of the parent class. This table has columns for every attribute in all the classes in the inheritance model. Let's consider the following superclass and its subclasses:

@Entity
public class Person {
  @Id
  @GeneratedValue
  private long id;
  
  private String firstname;
  private String lastname;

}
  
@Entity
public class Driver extends Person {

  @Column(name="LIC_NUM")
  private String licenseNumber;

}

@Entity
public class Passenger...

Enumeration and custom data type

In this section, we see how to map "constants" to enumerated types. Constants are considered a small finite set of data elements, such as gender (Male, Female) or days of the week, such as Monday, Tuesday, and so on. Hibernate supports using enumerated types for mapping database columns containing data in a finite closed set. (The definition of a closed set comes straight from set theory.)

If you don't wish to use enumerated types, you can create a custom data type to map your data to a primitive type in Java, and you'll see that after we discuss the enumerated type.

Enumerated type

You can define an enumeration in Java and let Hibernate handle the mapping of "constants". JPA supports two kinds of enum: ORDINAL and STRING. If you use the ORDINAL enumeration type, the data in the mapped column is assumed to be an integer. You can guess how the STRING enumeration type behaves:

public enum WeekDay {
  Monday, Tuesday, Wednesday, Thursday...

Mapping concepts


Mapping objects to relations is the core mission of Hibernate, and as we discussed previously, this can be a difficult challenge that can only be overcome by understanding the fundamental concepts.

Let's explore mapping concepts by reviewing some of the fundamentals of relational databases, such as relational algebra, simple and composite IDs, join tables, and foreign keys.

Instances and rows

The origin of relational database concepts is Relational Algebra, which is based on Set Theory. Just as we think of objects as instances of classes, you should also think of a database row (a tuple) as an element of a set (the relation) that is defined by the database tab.

For example, if your object graph contains an instance of the Person entity class that represents John and another instance that represents Sara, you should think of these as two rows in the Person table.

In both cases, by being an instance of a class or a row of a table, they agree to possess certain attributes, such...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Understand the internals of Hibernate and its architecture, and how it manages Entities, Events, Versioning, Filters, and Cache
  • Observe how Hibernate bridges the gap between object-oriented concepts and relational models
  • Discover how Hibernate can address architectural concerns such as Transaction, Database Multi-tenancy, Clustering, and Database Shards

Description

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.

Who is this book for?

Mastering Hibernate is intended for those who are already using or considering using Hibernate as the solution to address the problem of Object Relational Mapping. If you are already using Hibernate, this book will help you understand the internals and become a power user of Hibernate.

What you will learn

  • Understand the internals of a Hibernate session and how Entities are managed
  • Declare better mapping between entity classes and database tables
  • Manage entity associations and collections
  • Fetch data not just by entity ID, but also using HQL, Criteria Objects, Filters, and Native SQL
  • Observe the first and second level caches and find out how to manage them
  • Collect statistics and metrics data for further observation
  • Make your application work with multi-tenant databases

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 16, 2016
Length: 204 pages
Edition : 1st
Language : English
ISBN-13 : 9781785288753
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 : May 16, 2016
Length: 204 pages
Edition : 1st
Language : English
ISBN-13 : 9781785288753
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
Mastering Hibernate
€24.99
Java Hibernate Cookbook
€36.99
Learning Network Programming with Java
€41.99
Total 103.97 Stars icon
Banner background image

Table of Contents

10 Chapters
1. Entity and Session Chevron down icon Chevron up icon
2. Advanced Mapping Chevron down icon Chevron up icon
3. Working with Annotations Chevron down icon Chevron up icon
4. Advanced Fetching Chevron down icon Chevron up icon
5. Hibernate Cache Chevron down icon Chevron up icon
6. Events, Interceptors, and Envers Chevron down icon Chevron up icon
7. Metrics and Statistics Chevron down icon Chevron up icon
8. Addressing Architecture Chevron down icon Chevron up icon
9. EJB and Spring Context Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(1 Ratings)
5 star 0%
4 star 0%
3 star 100%
2 star 0%
1 star 0%
CM Aug 20, 2016
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
The book doesn't get into any details of really mastering n Hibernate but is a good book for reference.
Amazon Verified review Amazon
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.