Fisher Murphy Spring Persistence with Hibernate Companion eBook Available this print for content only—size & color not accurate CYAN MAGENTA YELLOW BLACK PANTONE 123 C BOOKS FOR PROFESSIONALS BY PROFESSIONALS ® US $44.99 Shelve in: Java Programming User level: Intermediate–Advanced www.apress.com SOURCE CODE ONLINE Companion eBook See last page for details on $10 eBook version ISBN 978-1-4302-2632-1 9 781430 226321 54499 Spring Persistence with Hibernate Dear Reader, Persistence is the foundation upon which many applications are built. The suc- cess or failure of a project often hinges on how its persistence tier is architected. Spring and Hibernate take the guesswork out of designing these integral com- ponents, helping you to enforce solid coding practices and reduce coupling between layers or with external frameworks. Learning the fundamentals of these two amazing open-source frameworks is just the beginning. To get the very most out of Spring and Hibernate, you must understand how these components behave, and learn best practices for integrating them into an application. An efficient, flexible persistence tier can only be built on proven design patterns and strategies that address common requirements such as caching, lazy-loading, and transactional semantics. This book will not only teach you the features of Spring 3 and Hibernate 3.5, it will also guide you through the essential steps of building a real-world appli- cation—addressing common pitfalls and considerations along the way. We will introduce you to best practices and tricks that we have learned from years of hands-on experience, and that you too can apply to your own projects. As a bonus, you will also learn about two exciting state-of-the-art projects that build upon Spring and Hibernate: Grails and Roo. Spring and Hibernate are two of the most popular open-source frameworks, for very good reasons. This book will show you why so many Java projects rely on them, and teach you how to reap the even greater benefits of using them together. Paul Tepper Fisher Paul Tepper Fisher, Author of Spring Persistence — A Running Start Brian D. Murphy 7.5 x 9.25 spine = 0.71875" 264 page count THE EXPERT’S VOICE ® IN OPEN SOURCE Spring Persistence with Hibernate Paul Tepper Fisher and Brian D. Murphy Guides you through the essential aspects and best practices of building a real application, using Spring Framework 3, Hibernate 3.5, Grails, and Roo Covers Spring 3, Hibernate 3.5, Grails, and Roo! THE APRESS ROADMAP Spring Persistence with Hibernate Spring Recipes, Second Edition Hibernate Recipes Beginning Hibernate, Second Edition Beginning Spring www.it-ebooks.info www.it-ebooks.info Spring Persistence with Hibernate ■ ■ ■ PAUL TEPPER FISHER BRIAN D. MURPHY www.it-ebooks.info ii Spring Persistence with Hibernate Copyright © 2010 by Paul Tepper Fisher and Brian D. Murphy All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13 (pbk): 978-1-4302-2632-1 ISBN-13 (electronic): 978-1-4302-2633-8 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 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. President and Publisher: Paul Manning Lead Editors: Steve Anglin, Tom Welsh Technical Reviewer: Sia Cyrus Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh Coordinating Editor: Mary Tobin Copy Editor: Marilyn Smith Compositor: Kimberly Burton Indexer: Julie Grady Artist: April Milne Cover Designer: Anna Ishchenko Distributed to the book trade worldwide by Springer Science+Business Media, LLC., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer- sbm.com, or visit www.springeronline.com. For information on translations, please e-mail rights@apress.com, 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/info/bulksales. The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. The source code for this book is available to readers at www.apress.com. You will need to answer questions pertaining to this book in order to successfully download the code. www.it-ebooks.info To Melanie, for making it all worthwhile —Paul I would like to dedicate this, my first print book, to my mom. I miss you always —Brian www.it-ebooks.info i v Contents at a Glance ■About the Authors xii ■About the Technical Reviewer xiii ■Acknowledgments xiv ■Preface xvi ■Chapter 1: Architecting Your Application with Spring, Hibernate, and Patterns 1 ■Chapter 2: Spring Basics 17 ■Chapter 3: Basic Application Setup 33 ■Chapter 4: Persistence with Hibernate 49 ■Chapter 5: Domain Model Fundamentals 69 ■Chapter 6: DAOs and Querying 85 ■Chapter 7: Transaction Management 109 ■Chapter 8: Effective Testing 125 ■Chapter 9: Best Practices and Advanced Techniques 137 ■Chapter 10: Integration Frameworks 155 ■Chapter 11: GORM and Grails 189 ■Chapter 12: Spring Roo 215 ■Index 235 www.it-ebooks.info v Contents ■About the Authors xii ■About the Technical Reviewer xiii ■Acknowledgments xiv ■Preface xv ■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 12 The Active-Record Pattern 14 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 20 Understanding Bean Scopes 22 Dependency Injection and Inversion of Control 24 Setter-Based Dependency Injection 24 www.it-ebooks.info ■ CONTENTS vi vi Constructor-Based Dependency Injection 25 Instance Collaboration 26 Coding to Interfaces 27 Dependency Injection via Autowiring 28 @Annotation-Based Dependency Injection 29 Set It and Forget It! 30 Injecting Code Using AOP and Interceptors 31 Summary 32 ■Chapter 3: Basic Application Setup 33 Application Management with Maven 33 Managed Dependencies 33 Standard Directory Structure 35 POM Deconstruction 35 Spring Configuration 37 Namespace Support 38 Externalizing Property Configurations 38 Component Scanning 38 Import Statements 39 Database Integration 40 JDBC Support 40 Integration with JNDI 41 Web Application Configuration 43 Servlet Definition 44 Spring MVC 45 Summary 47 ■Chapter 4: Persistence with Hibernate 49 The Evolution of Database Persistence in Java 49 EJB, JDO, and JPA 50 www.it-ebooks.info ■ CONTENTS vii vii How Hibernate Fits In 52 JPA Interface Hierarchy 52 The Art Gallery Domain Model and DAO Structure 54 An @Entity-Annotated POJO 55 Simplified DAO Pattern with Generics 56 The Life Cycle of a JPA Entity 62 JPA Configuration 64 Bare-Bones JPA Setup 64 Spring Integration 66 Summary 68 ■Chapter 5: Domain Model Fundamentals 69 Understanding Associations 69 Building the Domain Model 71 Convention over Configuration 74 Managing Entity Identifiers 75 Using Cascading Options to Establish Data Relationships 76 Adding Second-Level Caching 77 Using Polymorphism with Hibernate 78 Summary 84 ■Chapter 6: DAOs and Querying 85 A Basic Hibernate DAO Implementation 85 Building a DAO 86 Using Spring’s Hibernate Support Classes 87 Enabling Query Caching with the HibernateTemplate 88 Going Template-less 89 Querying in Hibernate 92 Loading an Entity 93 Querying for a Particular Type 93 www.it-ebooks.info ■ CONTENTS viii viii Using Named Parameters 94 Querying Using Core Hibernate 95 Using Named Queries 96 Working with Polymorphic Queries 96 Persisting Data with Hibernate 97 Saving and Updating Data 97 Handling Binary Data 97 Understanding the Benefits of the Criteria API 98 Using the JPA 2.0 Criteria API 99 Summary 107 ■Chapter 7: Transaction Management 109 The Joy of ACID 110 Understanding Isolation Levels 111 Serializable 112 Repeatable Read 112 Read Committed 113 Read Uncommitted 113 Controlling ACID Reflux 113 Platform Transaction Management 114 Declarative Transaction Management 115 Programmatic Transaction Management 120 Transactional Examples 121 Creating a Batch Application 121 Using Two Datasources 122 Summary 123 ■Chapter 8: Effective Testing 125 Unit, Integration, and Functional Testing 126 Using JUnit for Effective Testing 127 www.it-ebooks.info [...]... companion for developers interested in learning about the Spring Framework and how it can be leveraged to build persistence- driven applications using Hibernate, one of the most popular Java persistence frameworks today Spring Persistence with Hibernate gets you rolling with fundamental Spring concepts, as well as proven design patterns for integrating persistence into your applications Many of the lessons... YOUR APPLICATION WITH SPRING, HIBERNATE, AND PATTERNS persistence functionality would be part of a DAO class, which helps to abstract the Hibernate- specific code from the rest of the application Although the HibernateTemplate and JpaTemplate provide an effective construct for streamlining persistence operations, they are no longer as necessary as they once were Hibernate 3 shipped with a feature called... development Hibernate provides a querying interface, using Hibernate Query Language (HQL) or the Hibernate Criteria API Together, Spring and Hibernate are a dynamic duo, capable of simplifying dependency collaboration, reducing coupling, and providing abstractions over persistence operations JPA is a Java standard for persistence, the design of which was significantly influenced by the Hibernate developers Hibernate. .. daunting task of integrating Hibernate into an application Thanks to Spring, the process of getting up and running with Hibernate became a great deal easier Developers could start with a Spring configuration file that not only bootstrapped a Hibernate SessionFactory (allowing configuration details to be specified via standard XML), but also streamlined the invocation of myriad Hibernate operations through... time-tested design patterns, such as HibernateTemplate and OpenSessionInView We will discuss these core SpringHibernate integration details in the next few chapters The important point here is that combining Spring and Hibernate affords developers an extremely powerful solution Not only does Spring simplify the integration of Hibernate, but it also reduces the coupling of Hibernate to an application If the... layering Each layer is focused specifically on accomplishing a particular task (with little knowledge or coupling to other layers within the application) The Layers of a Persistence Tier The application tier that deals with persistence is often called the persistence tier Spring helps to enforce a modular architecture in which the persistence tier is divided into several core layers that contain the following:... how to go about identifying and resolving these issues Hibernate- Search Sometimes, your application will require more than Hibernate or Spring have to offer So we will discuss some important frameworks that extend Spring and Hibernate, such as Hibernate- Search HibernateSearch integrates the popular open source search framework, Lucene, into a Hibernate or JPA application For features that require true... to offer Hibernate- Search seamlessly integrates Lucene into your persistence tier, allowing you to execute Lucene queries within the scope of a Hibernate Session or a JPA Persistence Context In Chapter 10, you will learn how this integration works, as well as the range of functionality afforded by Lucene and Hibernate- Search Building a REST Web Service Since many applications use Spring and Hibernate. .. exceptions that might occur in the transaction Without using Spring, much of your code has little to do with your persistence logic, but is the same boilerplate code required by each and every operation Spring s HibernateTemplate and JpaTemplate offer a series of convenience methods to streamline much of the common persistence- related functionality For example, the HibernateTemplate provides some useful methods... high-volume web applications using Spring and Hibernate One of the details that stands out in our joint experience is the importance and benefit of learning through hands-on experience To this end, we will build a real-world application that utilizes Spring 3, Hibernate 3.5, JPA 2.0, Hibernate- Search, Grails, Spring Roo, and Dozer We firmly believe that learning about Spring and Hibernate implies far more . Spring Framework 3, Hibernate 3.5, Grails, and Roo Covers Spring 3, Hibernate 3.5, Grails, and Roo! THE APRESS ROADMAP Spring Persistence with Hibernate Spring. Application with Spring, Hibernate, and Patterns 1 ■Chapter 2: Spring Basics 17 ■Chapter 3: Basic Application Setup 33 ■Chapter 4: Persistence with Hibernate