Joseph B. Ottinger,

Jeff Linwood and

Dave Minter

Beginning Hibernate

For Hibernate 5

4th ed.

Joseph B. Ottinger

Youngsville, North Carolina, USA

Jeff Linwood

Austin, Texas, USA

Dave Minter

London, UK

Any source code or other supplementary materials referenced by the author in this text are available to readers at www.apress.com . For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/ . Readers can also access source code at SpringerLink in the Supplementary Material section for each chapter.

ISBN 978-1-4842-2318-5

e-ISBN 978-1-4842-2319-2

DOI 10.1007/978-1-4842-2319-2

Library of Congress Control Number: 2016959194

© Joseph B. Ottinger, Jeff Linwood and Dave Minter 2016

This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.

The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use.

The publisher, the authors and the editors are safe to assume that the advice and information in this book are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or the editors give a warranty, express or implied, with respect to the material contained herein or for any errors or omissions that may have been made.

Printed on acid-free paper

Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.

Dedicated to recursive dedications found around the globe. Again. And, still, to my beloved wife.

Introduction

Hibernate is an amazing piece of software. With a little experience and the power of annotations, you can build a complex, database-backed system with disturbing ease. Once you have built a system using Hibernate, you will never want to go back to the traditional approaches.

While Hibernate is incredibly powerful, it presents a steep learning curve when you first encounter it—steep learning curves are actually a good thing because they impart profound insight once you have scaled them. Yet gaining that insight takes some perseverance and assistance.

Our aim in this book is to help you scale that learning curve by presenting you with the minimal requirements of a discrete Hibernate application, explaining the basis of those requirements, and walking you through an example application that is built using them. We then provide additional material to be digested once the fundamentals are firmly understood. Throughout, we provide examples rather than relying on pure discourse. We hope that you will continue to find this book useful as a reference text long after you have become an expert on the subject.

Who This Book Is For

This book assumes a good understanding of Java fundamentals and some slight familiarity with database programming using the Java Database Connectivity (JDBC) API. We don’t expect you to know anything about Hibernate—but if you buy this book, it will probably be because you have had some exposure to the painful process of building a large database-based system.

All of our examples use open—source software—primarily the Hibernate API itself—so you will not need to purchase any software to get started with Hibernate development. This book is not an academic text. Our focus is, instead, on providing extensive examples and taking a pragmatic approach to the technology that it covers.

To true newcomers to the Hibernate API, we recommend that you read at least the first three chapters in order before diving into the juicy subjects of later chapters. Very experienced developers or those with experience with tools similar to Hibernate will want to skim the latter half of the book for interesting chapters.

How This Book Is Structured

This book is informally divided into three parts. Chapters 1 through 8 describe the fundamentals of Hibernate, including configuration, the creation of mapping files, and the basic APIs. Chapters 9 through 11 describe the use of queries, criteria, and filters to access the persistent information in more sophisticated ways. Chapter 12 addresses the use of Hibernate to talk to nonrelational data stores, providing an easy "on ramp" to NoSQL.

Finally, the appendixes discuss features that you will use less often or that are peripheral to the core Hibernate functionality. The following list describes more fully the contents of each chapter:

Chapter 1 outlines the purpose of persistence tools and presents excerpts from a simple example application to show how Hibernate can be applied. It also introduces core terminology and concepts.

Chapter 2 discusses the fundamentals of configuring a Hibernate application. It presents the basic architecture of Hibernate and discusses how a Hibernate application is integrated into an application.

Chapter 3 presents an example application, walking you through the complete process of creating and running the application. It then looks at a slightly more complex example and introduces the notion of generating the database schema directly from Hibernate annotations.

Chapter 4 covers the Hibernate lifecycle in depth. It discusses the lifecycle in the context of the methods available on the core interfaces. It also introduces key terminology and discusses the need for cascading and lazy loading.

Chapter 5 explains why mapping information must be retained by Hibernate and demonstrates the various types of associations that can be represented by a relational database. It briefly discusses the other information that can be maintained within a Hibernate mapping.

Chapter 6 explains how Hibernate lets you use the annotations to represent mapping information. It provides detailed examples for the most important annotations, and discusses the distinctions between the standard JPA 2 annotations and the proprietary Hibernate ones.

Chapter 7 explains some of the uses of the Java Persistence API (as opposed to the Hibernate-native API), as well as the lifecycle and validation of persisted objects.

Chapter 8 revisits the Hibernate Session object in detail, explaining the various methods that it provides. The chapter also discusses the use of transactions, locking, and caching, as well as how to use Hibernate in a multithreaded environment.

Chapter 9 discusses how Hibernate can be used to make sophisticated queries against the underlying relational database using the built-in Hibernate Query Language (HQL).

Chapter 10 introduces the Criteria API, which is a programmatic analog of the query language discussed in Chapter 9 .

Chapter 11 discusses how the Filter API can be used to restrict the results of the queries introduced in Chapters 9 and 10 .

Chapter 12 introduces Hibernate OGM, which maps objects to non-relational data stores like Infinispan and Mongodb, among others. It shows some of the uses of Hibernate Search to provide a common search facility for NoSQL, as well as offering full text query support.

Chapter 13 covers Hibernate Envers, which is a library that provides versioned data for entities stored through hibernate.

Downloading the Code

The source code for this book is available to readers from www.apress.com , in the Source Code/Download section. Please feel free to visit the Apress web site and download all the code from there.

Contacting the Authors

We welcome feedback from our readers. If you have any queries or suggestions about this book, or technical questions about Hibernate, or if you just want to share a really good joke, you can email Joseph Ottinger at [email protected] , Dave Minter at [email protected], and Jeff Linwood at [email protected] .

Acknowledgments

Joseph would like to thank various people for encouraging and enabling him to write this book, and so he will: first, his wife and children for allowing him the time and energy to put into the project; various project leads for Hibernate like Steve Ebersole and Chris Cranford; Jonas Konrad, who provided some advice and muchneeded pointers in a few critical spots; friends like Tracy Snell, Andrew Lombardi, Eugene Ciurana, and Justin Lee for serving as sounding boards and source material; his editors, for putting up with his quirks 1 ; bands like Rush, Pink Floyd, and Porcupine Tree for providing the soundtrack to the book 2 ; the letter Z, for having one of the most fun letters’ names to pronounce 3 ; his Gibson guitars, because they care; and lastly, Stan Lee, for giving Joseph a worthwhile impetus to learn to read when he was very young.

Contents

  1. Chapter 1:​ An Introduction to Hibernate 5
    1. Plain Old Java Objects (POJOs)
    2. Origins of Hibernate and Object/​Relational Mapping
    3. Hibernate as a Persistence Solution
    4. A Hibernate Hello World Example
    5. Mappings
    6. Persisting an Object
    7. Summary
  2. Chapter 2:​ Integrating and Configuring Hibernate
    1. The Steps Needed to Integrate and Configure Hibernate
    2. Understanding Where Hibernate Fits into Your Java Application
    3. Deploying Hibernate
      1. Installing Maven
    4. Connection Pooling
    5. Summary
  3. Chapter 3:​ Building a Simple Application
    1. A Simple Application
      1. A First Attempt
      2. Writing Data
      3. Reading Data
      4. Updating Data
      5. Persistence Contexts
      6. Removing Data
      7. A Note on Transactions
      8. Writing Our Sample Application
    2. Summary
  4. Chapter 4:​ The Persistence Life Cycle
    1. Introducing the Life Cycle
    2. Entities, Classes, and Names
    3. Identifiers
    4. Entities and Associations
    5. Saving Entities
    6. Object Equality and Identity
    7. Loading Entities
    8. Merging Entities
    9. Refreshing Entities
    10. Updating Entities
    11. Deleting Entities
    12. Cascading Operations
    13. Lazy Loading, Proxies, and Collection Wrappers
    14. Querying Objects
    15. Summary
  5. Chapter 5:​ An Overview of Mapping
    1. Why Mapping Cannot Easily Be Automated
    2. Primary Keys
    3. Lazy Loading
    4. Associations
      1. The One-to-One Association
      2. The One-to-Many and Many-to-One Association
      3. The Many-to-Many Association
      4. Applying Mappings to Associations
    5. Other Supported Features
      1. Specification of (Database) Column Types and Sizes
      2. The Mapping of Inheritance Relationships to the Database
      3. Primary Key
      4. The Use of SQL Formula–Based Properties
      5. Mandatory and Unique Constraints
    6. Summary
  6. Chapter 6:​ Mapping with Annotations
    1. Creating Hibernate Mappings with Annotations
      1. The Cons of Annotations
      2. The Pros of Annotations
      3. Choosing Which to Use
    2. JPA 2 Persistence Annotations
      1. Entity Beans with @Entity
      2. Primary Keys with @Id and @GeneratedValue
      3. Compound Primary Keys with @Id, @IdClass, or @EmbeddedId
      4. Database Table Mapping with @Table and @SecondaryTable
      5. Persisting Basic Types with @Basic
      6. Omitting Persistence with @Transient
      7. Mapping Properties and Fields with @Column
      8. Modeling Entity Relationships
      9. Inheritance
      10. Other JPA 2 Persistence Annotations
      11. Ordering Collections with @OrderColumn
    3. Configuring the Annotated Classes
    4. Hibernate-Specific Persistence Annotations
      1. @Immutable
      2. Natural IDs
    5. Summary
  7. Chapter 7:​ JPA Integration and Lifecycle Events
    1. The Java Persistence Architecture
      1. The Project Object Model
      2. The JPASessionUtil Class
      3. Testing JPASessionUtil
    2. Lifecycle Events
    3. External Entity Listeners
    4. Data Validation
    5. Summary
  8. Chapter 8:​ Using the Session
    1. Sessions
    2. Transactions and Locking
      1. Transactions
      2. Locking
      3. Deadlocks
    3. Caching
    4. Threads
    5. Summary
  9. Chapter 9:​ Searches and Queries
    1. Hibernate Query Language (HQL)
    2. Syntax Basics
      1. UPDATE
      2. DELETE
      3. INSERT
      4. SELECT
    3. Named Queries
    4. Logging and Commenting the Underlying SQL
      1. Logging the SQL
      2. Commenting the Generated SQL
    5. The from Clause and Aliases
    6. The select Clause and Projection
    7. Using Restrictions with HQL
    8. Using Named Parameters
    9. Paging Through the Result Set
    10. Obtaining a Unique Result
    11. Sorting Results with the order by Clause
    12. Associations
    13. Aggregate Methods
    14. Bulk Updates and Deletes with HQL
    15. Using Native SQL
    16. Summary
  10. Chapter 10:​ Advanced Queries Using Criteria
    1. Using the Criteria API
      1. Using Restrictions with Criteria
      2. Paging Through the Result Set
      3. Obtaining a Unique Result
      4. Sorting the Query’s Results
    2. Associations
    3. Projections and Aggregates
    4. Should You Use the Criteria API?​
    5. Summary
  11. Chapter 11:​ Filtering the Results of Searches
    1. When to Use Filters
    2. Defining and Attaching Filters
      1. Filters with Annotations
      2. Filters with XML Mapping Documents
    3. Using Filters in Your Application
    4. A Basic Filtering Example
    5. Summary
  12. Chapter 12:​ Leaving the Relational Database Behind:​ NoSQL
    1. Where Is Hibernate When It Comes to NoSQL?​
      1. First Warning:​ NoSQL Is Not Relational, and Hibernate Is an ORM
      2. Hibernate Is not Perfect, or “Finished”
    2. Basic CRUD Operations
      1. The Tests
      2. Testing Create and Read
      3. Testing Updates
      4. Testing Removal
      5. Querying in OGM
    3. MongoDB
    4. What the Hibernate Native API for OGM Looks Like
    5. Summary
  13. Chapter 13:​ Hibernate Envers
    1. Making Envers Available to Your Project
    2. Storing a User Object
    3. Updating the User
    4. Accessing Envers Information
    5. Querying Audited Data
    6. Applying Audit Data
    7. Summary
  14. Index

About the Authors and About the Technical Reviewer

About the Authors

A321250_4_En_BookFrontmatter_Figb_HTML.jpg

Joseph B. Ottinger is a systems architect, consultant, and Knowledge Graph Architect with Cosmify. He’s been messing around with computers since the 1980s, thinking about systems and architecture through war games and music. He’s worked as a developer, architect, consultant, and writer since then, including editing stints at Java Developer Journal and TheServerSide.com.

A musician, programmer, artist, writer, father, and husband, his interests tend to range far and wide, through philosophy, history, science, art, basketball, education, and - apparently - hamsters.

A321250_4_En_BookFrontmatter_Figd_HTML.jpg

Jeff Linwood has been involved in software programming since he had a 286 in high school. He got caught up with the Internet when he got access to a UNIX shell account, and it has been downhill ever since.

When he’s not playing on the computer, his hobby is running ultramarathons. Jeff is based in Austin, Texas, and helps large companies solve tough problems with content management, search engines, and web application development. Jeff also co-authored Professional Struts Applications (Apress), Building Portals with the Java Portlet API (Apress), and Pro Hibernate 3 (Apress).

A321250_4_En_BookFrontmatter_Figc_HTML.jpg

Dave Minter has adored computers since he was small enough to play in the boxes they came in. He built his first PC from discarded, faulty, and obsolete components; and he considers that to be the foundation of his career as an integration consultant. Dave is based in London, where he helps large and small companies build systems that “just work.” He wrote Beginning Spring 2: From Novice to Professional (Apress) and co-authored Building Portals with the Java Portlet API (Apress) and Pro Hibernate 3 (Apress).

About the Technical Reviewer

A321250_4_En_BookFrontmatter_Fige_HTML.jpg

Massimo Nardone has more than 22 years of experiences in Security, Web/Mobile development, Cloud and IT Architecture. His true IT passions are Security and Android. He has been programming and teaching how to program with Android, Perl, PHP, Java, VB, Python, C/C++ and MySQL for more than 20 years. He holds a Master of Science degree in Computing Science from the University of Salerno, Italy.

He has worked as a Project Manager, Software Engineer, Research Engineer, Chief Security Architect, Information Security Manager, PCI/SCADA Auditor and Senior Lead IT Security/Cloud/SCADA Architect for many years.

His technical skills include: Security, Android, Cloud, Java, MySQL, Drupal, Cobol, Perl, Web and Mobile development, MongoDB, D3, Joomla, Couchbase, C/C++, WebGL, Python, Pro Rails, Django CMS, Jekyll, Scratch, etc. He currently works as Chief Information Security Office (CISO) for Cargotec Oyj.

He worked as visiting lecturer and supervisor for exercises at the Networking Laboratory of the Helsinki University of Technology (Aalto University). He holds four international patents (PKI, SIP, SAML and Proxy areas).

Massimo has reviewed more than 40 IT books for different publishing company and he is the coauthor of Pro Android Games (Apress, 2015).

Footnotes

1 . Quirks like his endless footnotes; when asked, they allowed Joseph to have one footnote for every three pages, to which the response was, "Thanks! Three footnotes maximum for every page, got it!"

2 . A soundtrack you won’t hear, nor is it likely to be easily detected unless you listen very well. Listen more than that—no, more than that, too. Keep going. Let me know which song you hear, okay?

3 Z is pronounced like “see.” He learned this from his youngest son.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset