Spring Persistence with Hibernate

T HE E X P ER T ’S VOIC E ® IN JAVA Spring Persistence with Hibernate Second Edition — Paul Fisher Brian D. Murphy Spring Persistence with Hibernat...
3 downloads 0 Views 395KB Size
T HE E X P ER T ’S VOIC E ® IN JAVA

Spring Persistence with Hibernate Second Edition — Paul Fisher Brian D. Murphy

Spring Persistence with Hibernate Second Edition

Paul Fisher Brian D. Murphy

Spring Persistence with Hibernate, Second Edition Paul Fisher Brookyln, New York USA

Brian D. Murphy Maplewood, New Jersey USA

ISBN-13 (pbk): 978-1-4842-0269-2

ISBN-13 (electronic): 978-1-4842-0268-5

DOI 10.1007/978-1-4842-0268-5 Library of Congress Control Number: 2016943012 Copyright © 2016 by Paul Fisher and Brian D. Murphy 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. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director: Welmoed Spahr Lead Editor: Steve Anglin Technical Reviewer: Vinay Kumar Editorial Board: Steve Anglin, Pramila Balan, Louise Corrigan, Jonathan Gennick, Robert Hutchinson, Celestin Suresh John, Michelle Lowman, James Markham, Susan McDermott, Matthew Moodie, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Gwenan Spearing Coordinating Editor: Mark Powers Copy Editor: Kim Burton-Weisman Compositor: SPi Global Indexer: SPi Global Artist: SPi Global 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. For information on translations, please e-mail [email protected], or visit www.apress.com. Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales. Any source code or other supplementary materials referenced by the author in this text is available to readers at www.apress.com/9781484202692. 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. Printed on acid-free paper

Contents at a Glance About the Authors.................................................................................................... xi About the Technical Reviewer ............................................................................... xiii Acknowledgments ...................................................................................................xv Preface ..................................................................................................................xvii ■ Chapter 1: Architecting Your Application with Spring, Hibernate, and Patterns .......................................................................................................... 1 ■Chapter 2: Spring Basics ..................................................................................... 17 ■Chapter 3: Basic Application Setup ..................................................................... 35 ■Chapter 4: Persistence with Hibernate ................................................................ 55 ■Chapter 5: Domain Model Fundamentals............................................................. 85 ■Chapter 6: Transaction Management................................................................. 109 ■Chapter 7: Effective Testing ............................................................................... 127 ■Chapter 8: Best Practices and Advanced Techniques........................................ 141 Index ..................................................................................................................... 161

iii

Contents About the Authors.................................................................................................... xi About the Technical Reviewer ............................................................................... xiii Acknowledgments ...................................................................................................xv Preface ..................................................................................................................xvii ■ Chapter 1: Architecting Your Application with Spring, Hibernate, and Patterns .......................................................................................................... 1 The Benefit of a Consistent Approach .............................................................................. 1 The Significance of Dependency Injection.............................................................................................. 2

A Synergistic Partnership ................................................................................................. 2 The Story of Spring’s and Hibernate’s Success ...................................................................................... 3 A Better Approach for Integration ........................................................................................................... 3 Best Practices for Architecting an Application........................................................................................ 4

Other Persistence Design Patterns ................................................................................ 12 The Template Pattern............................................................................................................................ 13 The Active-Record Pattern .................................................................................................................... 15

Summary ........................................................................................................................ 15 ■Chapter 2: Spring Basics ..................................................................................... 17 Exploring Spring’s Architecture ...................................................................................... 18 The Application Context ........................................................................................................................ 18 Beans, Beans, the Magical Fruit ........................................................................................................... 20 The Spring Life Cycle ............................................................................................................................ 21 Understanding Bean Scopes ................................................................................................................ 22

v

■ CONTENTS

Dependency Injection and Inversion of Control .............................................................. 24 Setter-Based Dependency Injection ..................................................................................................... 24 Constructor-Based Dependency Injection............................................................................................. 25 Instance Collaboration .......................................................................................................................... 26 Coding to Interfaces ............................................................................................................................. 27 Dependency Injection via Autowiring ................................................................................................... 29 Code-Based Dependency Injection ....................................................................................................... 29 Set It and Forget It! ............................................................................................................................... 32

Injecting Code Using AOP and Interceptors .................................................................... 33 Summary ........................................................................................................................ 34 ■Chapter 3: Basic Application Setup ..................................................................... 35 Application Management with Maven ............................................................................ 35 Managed Dependencies ....................................................................................................................... 35 Standard Directory Structure................................................................................................................ 37 POM Deconstruction ............................................................................................................................. 37

Spring Configuration ...................................................................................................... 41 Namespace Support ............................................................................................................................. 43 Externalizing Property Configurations .................................................................................................. 44 Component Scanning ........................................................................................................................... 44 Import Statements ................................................................................................................................ 45

Database Integration ...................................................................................................... 45 JDBC Support ....................................................................................................................................... 46 Integration with JNDI ............................................................................................................................ 47

Web Application Configuration ....................................................................................... 49 Servlet Definition .................................................................................................................................. 51 Spring MVC ........................................................................................................................................... 52

Summary ........................................................................................................................ 54

vi

■ CONTENTS

■Chapter 4: Persistence with Hibernate ................................................................ 55 The Evolution of Database Persistence in Java.............................................................. 55 EJB, JDO, and JPA ................................................................................................................................. 56 How Hibernate Fits In ........................................................................................................................... 58

JPA Interface Hierarchy .................................................................................................. 58 The Audio Manager Domain Model and DAO Structure .................................................. 59 An @Entity-Annotated POJO ................................................................................................................. 60 Simplified DAO Pattern with Generics .................................................................................................. 64 The Life Cycle of a JPA Entity ............................................................................................................... 67

JPA Configuration ........................................................................................................... 68 Bare-Bones JPA Setup.......................................................................................................................... 69 Spring Integration ................................................................................................................................. 71 Querying and DAO Strategies ............................................................................................................... 75 Looking at the JPA Criteria API ............................................................................................................. 75 Using the JPA 2.0 Criteria API ............................................................................................................... 76 Using QueryDSL .................................................................................................................................... 79 Integrating QueryDSL with Spring ........................................................................................................ 82

Summary ........................................................................................................................ 84 ■Chapter 5: Domain Model Fundamentals............................................................. 85 Understanding Associations ........................................................................................... 85 Building the Domain Model ............................................................................................ 87 Polymorphism in JPA ............................................................................................................................ 92 Convention over Configuration ............................................................................................................. 94 Managing Entity Identifiers................................................................................................................... 96 Using Cascading Options to Establish Data Relationships ................................................................... 97 Adding Second-Level Caching .............................................................................................................. 97 Using Polymorphism with Hibernate .................................................................................................... 98

Summary ...................................................................................................................... 107

vii

■ CONTENTS

■Chapter 6: Transaction Management................................................................. 109 The Joy of ACID ............................................................................................................ 110 Understanding Isolation Levels .................................................................................... 110 Serializable ......................................................................................................................................... 112 Repeatable Read ................................................................................................................................ 112 Read Committed ................................................................................................................................. 112 Read Uncommitted ............................................................................................................................. 112

Controlling ACID Reflux................................................................................................. 113 Platform Transaction Management ..................................................................................................... 113 Declarative Transaction Management ................................................................................................ 114 Programmatic Transaction Management ............................................................................................ 122

Transactional Examples................................................................................................ 123 Creating a Batch Application .............................................................................................................. 123 Using Two Datasources ...................................................................................................................... 124

Summary ...................................................................................................................... 125 ■Chapter 7: Effective Testing ............................................................................... 127 Unit, Integration, and Functional Testing ...................................................................... 127 Using JUnit for Effective Testing................................................................................... 129 Unit Testing with Mocks...................................................................................................................... 131 Spring Dependency Injection and Testing........................................................................................... 133 Integration Testing with a Database ................................................................................................... 135 Integration Testing for RESTful APIs ................................................................................................... 137

Summary ...................................................................................................................... 139 ■Chapter 8: Best Practices and Advanced Techniques........................................ 141 Lazy Loading Issues ..................................................................................................... 141 The N+1 Selects Problem ................................................................................................................... 142 Lazy Initialization Exceptions.............................................................................................................. 147

viii

■ CONTENTS

Caching ........................................................................................................................ 150 Integrating a Caching Implementation ............................................................................................... 151 Caching Your Queries.......................................................................................................................... 155 Caching in a Clustered Configuration ................................................................................................. 156

Summary ...................................................................................................................... 159 Index ..................................................................................................................... 161

ix

About the Authors Paul Tepper Fisher first began working in technology at Johns Hopkins University, where he spent several years developing a distance learning platform, while completing graduate school there. Currently, Paul is the CTO at Recombine, a genetics testing company in New York City with a mission to expand the scope and impact of genomics in medicine. Before joining Recombine, Paul was the CTO at Onswipe, a mobile publishing platform, which was acquired by Beanstock Media in 2014. Prior to Onswipe, Paul was the CTO at Sonar Media — one of the first mobile social discovery platforms, which provided real-time notifications about relevant people nearby. Before joining Sonar, Paul was the CTO at K2 MediaLabs, a mobile-focused venture fund where he oversaw K2’s profile companies — including Sonar, Marketsharing, and Tracks. Prior to K2, Paul was the Director of Engineering at Lime Wire, a Peer-to-Peer file-sharing company, where he led seven engineering teams for the development of a cloud-based Streaming Music Service. Previously, Paul managed the technology division for Wired Digital (owned by Condé Nast Publications), growing and overseeing the co-located development teams in both New York and San Francisco for Wired.com, Webmonkey.com, and howto.wired. com, helping wired.com triple its traffic to 12 million users. In 2004, Paul founded DialMercury.com, a real-time communications and telephony platform. In 1998, Paul co-founded SmartPants Media, Inc., a software development company focused on distance learning, video streaming, and interactive products, winning numerous awards, including a coveted Muse Award for the creation of an educational software application built for the Smithsonian Institution. Paul has co-written two technology books, both published by Apress: Spring Persistence — A Running Start, and Spring Persistence with Hibernate. Paul lives in Brooklyn, New York with his wife Melanie and daughter Madeleine. Brian D. Murphy has been enamored with computers and programming since he got his first computer, an Apple IIc, in 1984. He graduated from Rutgers University with a BS in computer science. He has focused on web development in a variety of settings ranging from early-stage startups to large, multinational corporations in fields covering e-commerce, consulting, finance, and media. He was an early adopter of Spring and Hibernate, and he has used both frameworks on large production systems since 2003. In his present role, Brian is the chief architect and director of engineering at Condé Nast, where he oversees the web and mobile presence for 25 award-winning brands, such as WIRED, The New Yorker, Epicurious, and Vanity Fair. He and his team leverage both Spring and Hibernate to power all of Condé Nast’s online products, drawing tens of millions of unique visitors each month. Brian deals with the challenges of building and operating scalable, distributed systems every single day. Brian lives in Maplewood, New Jersey, with his wife, Dania, son, Liam, and their dog, Cooper.

xi

About the Technical Reviewer Vinay Kumar is a technology evangelist. He has extensive, eight-plus years’ experience in designing and implementing large-scale enterprise technology projects in various consulting and system integration companies. His passion helped him achieve certifications in Oracle ADF, WebCenter Portal, and Java/ Java EE. Experience and in-depth knowledge has helped him evolve into a focused domain expert and a well-known technical blogger. He loves to spend time mentoring, writing technical blogs, publishing white papers, and maintaining a dedicated education channel on YouTube about ADF/WebCenter. In addition to experience in Java/Java EE, he is versed in various OpenStack technologies as well. Vinay has contributed to the Java/Oracle ADF/WebCenter community by publishing more than 300 technical articles on his personal blog at www.techartifact.com. He was awarded Oracle ACE in June 2014. You can follow him at @vinaykuma201 or in.linkedin.com/in/vinaykumar2.

xiii

Suggest Documents