Mastering Hibernate - Ramin Rad - E-Book

Mastering Hibernate E-Book

Ramin Rad

0,0
26,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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

About This Book

  • 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

Who This Book Is 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

In Detail

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.

Style and approach

This book takes a close look at the core topics, and helps you understand the complex topics by showing you examples and giving you in-depth discussions.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 238

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Mastering Hibernate
Credits
About the Author
About the Reviewers
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Entity and Session
Why this book?
Quick Hibernate
Working with a session
Session internals
Contextual session
Session per request
Session per conversation
Session per operation
Stateless session
Entity
Entity lifecycle
Types of entities
Identity crisis
Beyond JPA
Proxy objects
Batch processing
Manual batch management
Setting batch size
Using stateless session
Summary
2. Advanced Mapping
Mapping concepts
Instances and rows
Annotation versus XML
Owning entity
Value mapping
JPA ID generation
Hibernate ID generation
Composite ID
Association cardinality
One-to-one associations
One-to-many associations
Many-to-one associations
Many-to-many associations
Self-referencing tables
Cascade operations
Inheritance
Single table strategy
Table per class strategy
Joined strategy
Enumeration and custom data type
Enumerated type
Custom data type mapping
Summary
3. Working with Annotations
Mapping and association
@Any and @ManyToAny
@MapsId
@Fetch
@OrderBy
@ElementCollection and @CollectionTable
Behavior
@Cache
@Access
@Cascade
@CreationTimestamp and @UpdateTimestamp
@Filter and @FilterDef
@Immutable
@Loader
@NotFound
@SortComparator and @SortNatural
SQL/DDL modifier
@Check
@ColumnDefault
@ColumnTransformer
@DynamicInsert and @DynamicUpdate
@Formula
@SelectBeforeUpdate
@SQLDelete and @Where
@SQLInsert and @SQLUpdate
@SubSelect and @Synchronize
@WhereJoinTable
@NaturalId
Summary
4. Advanced Fetching
Fetching strategy
The JOIN fetch mode
The SELECT fetch mode
The SUBSELECT fetch mode
Batch fetching
Hibernate Query Language
Fetch queries
Delete and update
Join
Native SQL
Scalar query
Entity query
Criteria objects
Filters
Pagination
Summary
5. Hibernate Cache
Cache structure
Cache scope
First-level cache
Second-level cache
Cache provider interface
Ehcache implementation
Cache configuration
Query cache
Caching benefits and pitfalls
Caching strategies
Read only
Non-strict read write
Read-write
Transactional
Object identity
Managing the cache
Remove cached entities
Cache modes
Cache metrics
Summary
6. Events, Interceptors, and Envers
Services
Service loader
Service registry
The OSGi model
Events
Event listener
Registering listeners
Interceptors
Database trigger
Event or interceptor
Envers
Configuration
Strategy
Fetching revisions
Summary
7. Metrics and Statistics
Statistical data types
Session
Entity
Collection
Query
Cache
Statistics via JMX
Introduction to JMX
Using JMX with Hibernate
Summary
8. Addressing Architecture
Architecture matters
Transaction management
Local transactions
The Java Transaction API
Compensating transactions
Concurrency
Isolation levels
Locking
User lock
Scalability
Clustering
Database shards
Configuration
Sharded session factory
Shard strategy
Shard ID generation
Performance
Lazy loading
Fetch mode
Batch processing
Caching
Stateless session
Legacy application
Reverse engineering
Modernization
The Cloud strategy
Licensing
Multi-tenancy
Summary
9. EJB and Spring Context
Deployment
Configuration
Resource
Transaction
Hibernate libraries
EJB
Persistence unit
Server resources
Entity manager
Transaction
Hibernate session
Spring
Configuration
Transaction management
Data source
Session factory
Summary
Index

Mastering Hibernate

Mastering Hibernate

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: May 2016

Production reference: 1100516

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78217-533-9

www.packtpub.com

Credits

Author

Ramin Rad

Reviewers

Luca Masini

Sherwin John Calleja-Tragura

Aurélie Vache

Commissioning Editor

Neil Alexander

Acquisition Editor

Reshma Raman

Content Development Editor

Zeeyan Pinheiro

Technical Editor

Pranjali Mistry

Copy Editor

Pranjali Chury

Project Coordinator

Francina Pinto

Proofreader

Safis Editing

Indexer

Rekha Nair

Production Coordinator

Manu Joseph

Cover Work

Manu Joseph

About the Author

Ramin Rad has been working as a software professional for the last 20 years, living in Washington DC area. He studied mathematics and computer science in the academic world, and he cares deeply for the art of software development.

He is also a musician, a guitarist, who performs regularly in the DC area and beyond. His artistic side is significant because he believes that writing software is more art than science, following the philosophy of the likes of Donald Knuth, who wrote the Art of Computer Programming series.

Currently, he is a director and a solution architect at a large international software product and services company, focusing on enterprise, mobile, and cloud-based solutions.

I would like to thank three people who have made a significant impact on my professional life and career: my friend, Terry Rice, who always encouraged me to think scientifically and redirect my focus toward software architecture; my idol, Dr. Paul Eggert, who for me is a true computer scientist and with whom I had the pleasure of working; and finally my mentor, Jon King, who has guided me the most throughout my career and personal life.

Finally, I dedicate this book to my beautiful children, Mina and Cyrus. I hope when you grow up, you too love and learn all about life, nature, and science, and share what you learn with the world.

About the Reviewers

Luca Masini is a senior software engineer and architect. He started off as a game developer for Commodore 64 (Football Manager) and Commodore Amiga (Ken il guerriero). He soon converted to object oriented programming, and for that, from its beginning in 1995, he was attracted by the Java language.

Following his passion, he worked as a consultant for major Italian banks, developing and integrating the main software projects for which he has often taken technical leadership. He encouraged the adoption Java Enterprise in environments where COBOL was the flagship platform, converting them from mainframe centric to distributed.

He then shifted his focus toward open source, starting from Linux and then moving to enterprise frameworks with which he was able to introduce concepts such as IoC, ORM, and MVC with low impact. For that, he was an early adopter of Spring, Hibernate, Struts, and a whole host of other technologies that in the long run have given his customers a technological advantage and, therefore, development cost reduction.

After introducing new technology, he decided that it was time for simplification and standardization of development with Java EE, and as such, he's now working in the ICT of a large Italian company, where he has introduced build tools (Maven and continuous integration), archetypes of project, and agile development with plain standards.

Finally, he has focused his attention on mobilizing the enterprise and is now working on a whole set of standard and development processes to introduce mobile concepts and applications for sales force and management.

He has worked on the following books by Packt Publishing:

Securing WebLogic Server 12cGoogle Web ToolkitSpring Web Flow 2Spring Persistence with HibernateSpring Batch EssentialsSpring Integration Essentials

Sherwin John Calleja-Tragura has been a software consultant, technical trainer, and software analyst specializing in Java/JEE and Android specification. He started his career as a lecturer and numerical analyst at the University of the Philippines, Los Baños (UPLB), emphasizing on optimization of linear algorithms. In 2006, he became one of the Documentum and Alfresco consultants at Ayala Systems and Technology Inc. (ASTI) in Manila, Philippines. Currently, he is a technical consultant at Alibata Solutions and Technology Services Inc. and a Java/JEE technical trainer at Software Laboratory Inc. (SLI).

He has technically edited books such as Delphi Cookbook,,Alfresco 3 Records Management, and Alfresco Share, all by Packt Publishing.

He has taken 30 course units of masters of science in the computer science curriculum of UPLB.

I would like to thank my grandmother, Lila Calleja, for the continuous support and prayers for the success of all my work and my father, Cesar Tragura, for his encouragement and perseverance. I'd also like to thank Owen Salvador Estabillo, Matthew Jeoffrey Domino, Mark Joseph Ikang Fernandez, and Rostan Valdez for building my confidence and boosting my morale.

Aurélie Vache is a full-stack developer, working for atchikservices in Toulouse, France. She has been working as a developer for over 10 years.

A former Java/JEE developer, she has been developing business and social apps, backend and frontends services, websites, and lead technical projects. She has also been giving attention to UX and SEO, managing QoS (quality of service), and deploying apps in production for several years now. She is also a DevOps and enjoys Big Data technologies.

As a Duchess France Leader, she is strongly involved with Duchess France (www.duchess-france.org), an association promoting women developers and women in IT, inspiring and encouraging them to speak at conferences or technical events. The Duchess France team has launched a new coaching initiative (#AdoptADuchess) in order to help junior devlopers.

You can meet her at meetups in Toulouse, specifically at JUG, DevOps, and Toulouse Data Science, where she has already talked about Google BigQuery, the Big Data analytics as a service (AaaS) Google technology.

A couple of months ago, she was a member of the jury for the Senat (French Senate) IT developer contest in order to recruit two developers in the Information Systems Department (ISD).

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

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.

Conventions

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:

@Entity public class Person { @Id @GeneratedValue 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:

{ Entity public class Circle { @Id @GeneratedValue } }

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

selectcourse0_.id as id1_0_0_,course0_.title as title2_0_0_,students1_.course_id as course_i4_0_1_,students1_.id as id1_1_1_,students1_.gender as gender2_1_2_,students1_.name as name3_1_2_ fromCourse course0_

Note

Warnings or important notes appear in a box like this.

Tip

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 <[email protected]>, 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 www.packtpub.com/authors.

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 http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.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 WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

Errata

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 http://www.packtpub.com/submit-errata, 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 https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

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 <[email protected]> with a link to the suspected pirated material.

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

Questions

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

Chapter 1. Entity and Session

In this chapter, we will take an in-depth look at sessions and entities and their lifecycles. It is important to understand the concepts of session and entity when we talk about design concepts, such as session-per-request, session-per-conversation, stateless sessions, and contextual sessions, and discuss the various states of an entity. After all, the only way to master anything is by paying attention to the details. We also explore entities beyond their JPA characteristics and look at Hibernate entities to see the benefits of one over the other. Furthermore, we discuss proxy objects and how they are used.

In this chapter, we will cover the following topics:

Why this book?Quick HibernateHibernate session:
Session internalsContextual sessionsSessions per request, per conversation, and per operationStateless sessions
Hibernate entities:
Entity lifecycleTypes of entitiesIdentity crisisBeyond JPA
Proxy objectsBatch processing:
Manual batch managementSetting the size of the batch
Using a stateless session

Why this book?

Java developers solve problems using object-oriented concepts. We design applications using classes to model business entities. Furthermore, we utilize inheritance to imply that a class is another kind of class, or is composed of primitive fields and other classes, and visualize the application data as objects or object graphs. However, we also have a persistence problem.

Traditionally, the storage unit is implemented using structured records (tuples), which are stored in tables (relations) that may or may not be associated with each other. This concept is supported by a declarative language, which is limited in scope and is primarily for data creation and data manipulation. Tuples and objects have a lot in common; they both have attributes (columns and fields), and the attributes have data types (int, char, and so on), but the persistence problem becomes evident when you look at the differences between tuples and objects, such as identity, equality, or inheritance.

Object-Relational Mapping is a hard problem. Luckily, Hibernate makes this easy. You probably discovered this by reading the first few chapters of the Hibernate online documents or another book; and as you have to meet tight deadlines, you reactively solve your problems when they surface by swiftly paging through a book, searching or posting on stackoverflow, or other online forums or blogs. You spent half a day trying to find your answer and then moved on until the next problem surfaced. I have done it, you have done it; we ALL do it.

However, what if you knew about the internals of Hibernate and how it works? You wouldn't need to know everything about Hibernate, but you would know exactly where to look quickly to find your answer, such as a dictionary.

This book was written to explore the fundamental concepts of Hibernate and discuss them in detail, so that next time you run into a problem, you can identify the issue and find the answer that you want quickly. For example, whether a problem is a mapping problem or just improper use of an annotation. Furthermore, you will design better software once you understand the internals of any framework that you decide to use.

The main objectives of this book are to help you understand Hibernate beyond the basics, make you appreciate the ORM problem, and show you why Hibernate is one of the best solutions that exists today. We focus more on the Hibernate API and occasionally explore the JPA counterpart. This book assumes that you have a basic understanding of Hibernate and have used it in the past, or you are currently using it. If this is not the case for you, please visit the Hibernate documentation online, as it offers guides to get started with Hibernate and more.

Working with a session

The core operations of Hibernate occur in the session. This is where connection to the database is obtained, Structured Query Language (SQL) statements are composed, type conversions are made, and where transactions and the persistence context are managed. Let's start by getting to know the internals of a Hibernate session.

Session internals

If you have written at least one Hibernate application in the past, you already know what an entity and a session are. However, most of the time, developers don't think about the session, the entity, and their lifecycles, or about what occurs inside a session when an entity is saved or updated. There are fundamental concepts that one must understand in order to utilize Hibernate effectively.

The Hibernate session is where persistence work is performed for each thread of execution, and it manages the persistence context. Therefore, it's not thread-safe; this means that multiple threads should not access or use the same session at the same time. As you may know, sessions are created by calling the session factory, and there is only one factory per storage unit, although you can have multiple session factories pointing to different databases.

Furthermore, the session is designed to be a short-lived object. This is an important constraint that is typically imposed by the database and the application server, and this is because there is always a timeout setting on connections and transactions. (There is even timeout setting at the Java Database Connectivity (JDBC) level. Furthermore, you have to worry about TCP Socket timeout.) Even though these settings are set to some number of seconds, you should still avoid long-running logics while the session is open because you may create contention in the database and impact the system performance altogether. Hibernate tries to protect you by not allocating any resources, such as database connections, unless they are absolutely needed. However, you still have to be mindful of the work that you do within the unit of persistence work. As long as you limit the code to persistence-related tasks while you have an open session, you will be fine.