Statistics
3
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-01-15

AuthorNicholas S. Williams

The comprehensive Wrox guide for creating Java web applications for the enterprise. This guide shows Java software developers and software engineers how to build complex web applications in an enterprise environment. Youll begin with an introduction to the Java Enterprise Edition and the basic web application, then set up a development application server environment, learn about the tools used in the development process, and explore numerous Java technologies and practices. The book covers industry-standard tools and technologies, specific technologies, and underlying programming concepts. Java is an essential programming language used worldwide for both Android app development and enterprise-level corporate solutions As a step-by-step guide or a general reference, this book provides an all-in-one Java development solution Explains Java Enterprise Edition 7 and the basic web application, how to set up a development application server environment, which tools are needed during the development process, and how to apply various Java technologies Covers new language features in Java 8, such as Lambda Expressions, and the new Java 8 Date & Time API introduced as part of JSR 310, replacing the legacy Date and Calendar APIs Demonstrates the new, fully-duplex WebSocket web connection technology and its support in Java EE 7, allowing the reader to create rich, truly interactive web applications that can push updated data to the client automatically Instructs the reader in the configuration and use of Log4j 2.0, Spring Framework 4 (including Spring Web MVC), Hibernate Validator, RabbitMQ, Hibernate ORM, Spring Data, Hibernate Search, and Spring Security Covers application logging, JSR 340 Servlet API 3.1, JSR 245 JavaServer Pages (JSP) 2.3 (including custom tag libraries), JSR 341 Expression Language 3.0, JSR 356 WebSocket API 1.0, JSR 303/349 Bean Validation 1.1, JSR 317/338 Java Persistence API (JPA) 2.1, full-text searching with JPA, RESTful and SOAP web services, Advanced

Tags
No tags
ISBN: 1118768434
Publisher: Wrox
Publish Year: 2014
Language: 英文
Pages: 938
File Format: PDF
File Size: 10.6 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
ffirs.indd 6 11-02-2014 09:02:59
Professional Java® for Web Applications Nicholas S. Williams ffirs.indd 1 19-02-2014 12:20:41
Professional Java® for Web applications Published by John Wiley & Sons, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2014 by John Wiley & Sons, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN: 978-1-118-65646-4 ISBN: 978-1-118-65651-8 (ebk) ISBN: 978-1-118-90931-7 (ebk) Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions. Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read. For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com. Library of Congress Control Number: 2013958292 Trademarks: Wiley, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. Java is a registered trademark of Oracle America, Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book. ffirs.indd 2 24-02-2014 12:36:52
About the Author Nick WilliAms is a Software Engineer for UL Workplace Health and Safety in Franklin, Tennessee. A computer science graduate from Belmont University, he has been active in commercial and open source software projects for more than 9 years. He is the founder of DNSCrawler.com, a site for free DNS and IP troubleshooting tools, and NWTS Java Code, an open source community that specializes in obscure Java libraries that meet niche needs. In 2010, the Nashville Technology Council named him the Software Engineer of the Year for Middle Tennessee. Nick is a committer for Apache Logging (including Log4j) and Jackson Data Processor JSR 310 Data Types. He has also contributed new features to Apache Tomcat 8.0, Spring Framework 4.0, Spring Security 3.2, Spring Data Commons 1.6, Spring Data JPA 1.4, and JBoss Logging 3.2; serves as a contributor on several other projects, including OpenJDK; and is a member of the Java Community Process (JCP). Nick currently lives in Tennessee with his wife Allison. You can find him on Twitter @Java_Nick. About the techNicAl editors JAke rAdAkovich joined UL Workplace Health and Safety in 2009, and currently serves as Software Developer on the Occupational Health Manager product. Prior to that, he was a research assistant at Middle Tennessee State University working on AlgoTutor, a web-based algorithm development tutoring system. He holds a BS in Computer Science and Mathematics from Middle Tennessee State University. You can follow Jake on Twitter @JakeRadakovich. mANuel JordAN elerA is an autodidactic developer and researcher who enjoys learning new technologies for his own experiments and creating new integrations. He won the 2010 Springy Award and was a Community Champion and Spring Champion in 2013. In his little free time, he reads the Bible and composes music on his guitar. Manuel is a Senior Member in the Spring Community Forums known as dr_pompeii. You can read about him and contact him through his blog and you can follow him on his Twitter account, @dr_pompeii. ffirs.indd 3 24-02-2014 12:36:53
AcquisitioNs editor Mary James ProJect editor Maureen Spears Tullis techNicAl editors Michael Jordan Elera Jake Radakovich techNicAl ProofreAder Jonathan Giles seNior ProductioN editor Kathleen Wisor coPy editor Apostrophe Editing Services editoriAl mANAger Mary Beth Wakefield freelANcer editoriAl mANAger Rosemarie Graham AssociAte director of mArketiNg David Mayhew mArketiNg mANAger Ashley Zurcher busiNess mANAger Amy Knies vice PresideNt ANd executive grouP Publisher Richard Swadley AssociAte Publisher Jim Minatel ProJect coordiNAtor, cover Todd Klemme ProofreAders Nancy Carrasco Josh Chase, Word One iNdexer Robert Swanson cover desigNer Wiley cover imAge iStockphoto.com/ElementalImaging credits ffirs.indd 4 24-02-2014 12:36:53
AckNoWledgmeNts thANks to... My wife Allison, whose unwavering support and persistent reminders about deadlines during this stressful year made this book possible. My parents and siblings, who told me that I could do anything I put my mind to. Drs. Joyce Blair Crowell and William Hooper, whose dedicated instruction and mentoring made my career possible. Dr. Sarah Ann Stewart, who believed in me when I thought surely calculus and proofs spelled doom for my education. Mrs. Lockhart, who inspired me to write. Jay, for introducing me to Mary, and to Mary and Maureen for making this book a reality. Jake, for being absurd. Oh, and for agreeing to be my technical editor. ffirs.indd 5 24-02-2014 12:36:53
ffirs.indd 6 24-02-2014 12:36:53
Contents IntroductIon xxiii Part I: CreatIng enterPrIse aPPlICatIons ChaPter 1: IntroduCIng Java Platform, enterPrIse edItIon 3 A Timeline of Java Platforms 3 In the Beginning 4 The Birth of Enterprise Java 5 Java SE and Java EE Evolving Together 6 Understanding the Most Recent Platform Features 9 A Continuing Evolution 13 Understanding the Basic Web Application Structure 13 Servlets, Filters, Listeners, and JSPs 13 Directory Structure and WAR Files 14 The Deployment Descriptor 15 Class Loader Architecture 16 Enterprise Archives 17 Summary 18 ChaPter 2: usIng Web ContaIners 19 Choosing a Web Container 19 Apache Tomcat 20 GlassFish 21 JBoss and WildFly 22 Other Containers and Application Servers 22 Why You’ll Use Tomcat in This Book 23 Installing Tomcat on Your Machine 23 Installing as a Windows Service 24 Installing as a Command-Line Application 24 Configuring a Custom JSP Compiler 26 Deploying and Undeploying Applications in Tomcat 27 Performing a Manual Deploy and Undeploy 28 Using the Tomcat Manager 28 ftoc.indd 7 11-02-2014 08:39:54
viii CONTENTS Debugging Tomcat from Your IDE 30 Using IntelliJ IDEA 30 Using Eclipse 35 Summary 39 ChaPter 3: WrItIng Your fIrst servlet 41 Creating a Servlet Class 42 What to Extend 42 Using the Initializer and Destroyer 45 Configuring a Servlet for Deployment 46 Adding the Servlet to the Descriptor 46 Mapping the Servlet to a URL 47 Running and Debugging Your Servlet 49 Understanding doGet(), doPost(), and Other Methods 51 What Should Happen during the service Method Execution? 51 Using HttpServletRequest 52 Using HttpServletResponse 55 Using Parameters and Accepting Form Submissions 56 Configuring your Application Using Init Parameters 61 Using Context Init Parameters 61 Using Servlet Init Parameters 62 Uploading Files from a Form 64 Introducing the Customer Support Project 65 Configuring the Servlet for File Uploads 65 Accepting a File Upload 68 Making Your Application Safe for Multithreading 69 Understanding Requests, Threads, and Method Execution 69 Protecting Shared Resources 70 Summary 71 ChaPter 4: usIng JsPs to dIsPlaY Content 73 <br /> Is Easier Than output.println(“<br />”) 74 Why JSPs Are Better 75 What Happens to a JSP at Run Time 76 Creating Your First JSP 78 Understanding the File Structure 78 Directives, Declarations, Scriptlets, and Expressions 79 Commenting Your Code 81 Adding Imports to Your JSP 82 ftoc.indd 8 11-02-2014 08:39:54
ix CONTENTS Using Directives 83 Using the <jsp> Tag 86 Using Java within a JSP (and Why You Shouldn’t!) 88 Using the Implicit Variables in a JSP 88 Why You Shouldn’t Use Java in a JSP 93 Combining Servlets and JSPs 94 Configuring JSP Properties in the Deployment Descriptor 94 Forwarding a Request from a Servlet to a JSP 97 A Note about JSP Documents (JSPX) 102 Summary 104 ChaPter 5: maIntaInIng state usIng sessIons 105 Understanding Why Sessions Are Necessary 106 Maintaining State 106 Remembering Users 107 Enabling Application Workflow 107 Using Session Cookies and URL Rewriting 107 Understanding the Session Cookie 108 Session IDs in the URL 110 Session Vulnerabilities 112 Storing Data in a Session 116 Configuring Sessions in the Deployment Descriptor 116 Storing and Retrieving Data 119 Removing Data 123 Storing More Complex Data in Sessions 125 Applying Sessions Usefully 129 Adding Login to the Customer Support Application 129 Detecting Changes to Sessions Using Listeners 133 Maintaining a List of Active Sessions 135 Clustering an Application That Uses Sessions 139 Using Session IDs in a Cluster 139 Understand Session Replication and Failover 141 Summary 142 ChaPter 6: usIng the exPressIon language In JsPs 143 Understanding Expression Language 144 What It’s For 144 Understanding the Base Syntax 145 Placing EL Expressions 146 Writing with the EL Syntax 147 ftoc.indd 9 11-02-2014 08:39:54
x CONTENTS Reserved Keywords 148 Operator Precedence 148 Object Properties and Methods 154 EL Functions 155 Static Field and Method Access 156 Enums 157 Lambda Expressions 157 Collections 158 Using Scoped Variables in EL Expressions 160 Using the Implicit EL Scope 161 Using the Implicit EL Variables 165 Accessing Collections with the Stream API 167 Understanding Intermediate Operations 168 Using Terminal Operations 170 Putting the Stream API to Use 171 Replacing Java Code with Expression Language 172 Summary 175 ChaPter 7: usIng the Java standard tag lIbrarY 177 Introducing JSP Tags and the JSTL 178 Working with Tags 178 Using the Core Tag Library (C Namespace) 182 <c:out> 182 <c:url> 183 <c:if> 184 <c:choose>, <c:when>, and <c:otherwise> 185 <c:forEach> 186 <c:forTokens> 187 <c:redirect> 188 <c:import> 188 <c:set> and <c:remove> 189 Putting Core Library Tags to Use 190 Using the Internationalization and Formatting Tag Library (FMT Namespace) 193 Internationalization and Localization Components 193 <fmt:message> 194 <fmt:setLocale> 196 <fmt:bundle> and <fmt:setBundle> 196 <fmt:requestEncoding> 197 <fmt:timeZone> and <fmt:setTimeZone> 197 <fmt:formatDate> and <fmt:parseDate> 198 <fmt:formatNumber> and <fmt:parseNumber> 199 ftoc.indd 10 11-02-2014 08:39:54
xi CONTENTS Putting i18n and Formatting Library Tags to Use 200 Using the Database Access Tag Library (SQL Namespace) 203 Using the XML Processing Tag Library (X Namespace) 205 Replacing Java Code with JSP Tags 205 Summary 208 ChaPter 8: WrItIng Custom tag and funCtIon lIbrarIes 209 Understanding TLDs, Tag Files, and Tag Handlers 210 Reading the Java Standard Tag Library TLD 211 Comparing JSP Directives and Tag File Directives 217 Creating Your First Tag File to Serve as an HTML Template 219 Creating a More Useful Date Formatting Tag Handler 221 Creating an EL Function to Abbreviate Strings 226 Replacing Java Code with Custom JSP Tags 227 Summary 232 ChaPter 9: ImProvIng Your aPPlICatIon usIng fIlters 233 Understanding the Purpose of Filters 234 Logging Filters 234 Authentication Filters 234 Compression and Encryption Filters 234 Error Handling Filters 235 Creating, Declaring, and Mapping Filters 235 Understanding the Filter Chain 235 Mapping to URL Patterns and Servlet Names 236 Mapping to Different Request Dispatcher Types 236 Using the Deployment Descriptor 237 Using Annotations 238 Using Programmatic Configuration 238 Ordering Your Filters Properly 239 URL Pattern Mapping versus Servlet Name Mapping 239 Exploring Filter Order with a Simple Example 241 Using Filters with Asynchronous Request Handling 243 Investigating Practical Uses for Filters 247 Adding a Simple Logging Filter 248 Compressing Response Content Using a Filter 249 Simplifying Authentication with a Filter 254 Summary 255 ftoc.indd 11 11-02-2014 08:39:54
xii CONTENTS ChaPter 10: makIng Your aPPlICatIon InteraCtIve WIth WebsoCkets 257 Evolution: From Ajax to WebSockets 258 Problem: Getting New Data from the Server to the Browser 259 Solution 1: Frequent Polling 259 Solution 2: Long Polling 260 Solution 3: Chunked Encoding 262 Solution 4: Applets and Adobe Flash 263 WebSockets: The Solution Nobody Knew Kind of Already Existed 264 Understanding the WebSocket APIs 268 HTML5 (JavaScript) Client API 268 Java WebSocket APIs 270 Creating Multiplayer Games with WebSockets 273 Implementing the Basic Tic-Tac-Toe Algorithm 274 Creating the Server Endpoint 274 Writing the JavaScript Game Console 278 Playing WebSocket Tic-Tac-Toe 283 Using WebSockets to Communicate in a Cluster 284 Simulating a Simple Cluster Using Two Servlet Instances 284 Transmitting and Receiving Binary Messages 286 Testing the Simulated Cluster Application 287 Adding “Chat with Support” to the Customer Support Application 288 Using Encoders and Decoders to Translate Messages 289 Creating the Chat Server Endpoint 291 Writing the JavaScript Chat Application 294 Summary 296 ChaPter 11: usIng loggIng to monItor Your aPPlICatIon 297 Understanding the Concepts of Logging 298 Why You Should Log 298 What Content You Might Want to See in Logs 299 How Logs Are Written 301 Using Logging Levels and Categories 303 Why Are There Different Logging Levels? 303 Logging Levels Defined 303 How Logging Categories Work 304 How Log Sifting Works 305 Choosing a Logging Framework 305 API versus Implementation 305 ftoc.indd 12 11-02-2014 08:39:54
xiii CONTENTS Performance 306 A Quick Look at Apache Commons Logging and SLF4J 307 Introducing Log4j 2 307 Integrating Logging into Your Application 312 Creating the Log4j 2 Configuration Files 313 Utilizing Fish Tagging with a Web Filter 316 Writing Logging Statements in Java Code 317 Using the Log Tag Library in JSPs 319 Logging in the Customer Support Application 319 Summary 320 Part II: addIng sPrIng frameWork Into the mIx ChaPter 12: IntroduCIng sPrIng frameWork 323 What Is Spring Framework? 324 Inversion of Control and Dependency Injection 325 Aspect-Oriented Programming 325 Data Access and Transaction Management 325 Application Messaging 326 Model-View-Controller Pattern for Web Applications 326 Why Spring Framework? 326 Logical Code Groupings 326 Multiple User Interfaces Utilizing One Code Base 327 Understanding Application Contexts 327 Bootstrapping Spring Framework 329 Using the Deployment Descriptor to Bootstrap Spring 330 Programmatically Bootstrapping Spring in an Initializer 332 Configuring Spring Framework 336 Creating an XML Configuration 338 Creating a Hybrid Configuration 340 Configuring Spring with Java Using @Configuration 345 Utilizing Bean Definition Profiles 349 Understanding How Profiles Work 350 Considering Antipatterns and Security Concerns 352 Summary 353 ChaPter 13: rePlaCIng Your servlets WIth Controllers 355 Understanding @RequestMapping 356 Using @RequestMapping Attributes to Narrow Request Matching 356 Specifying Controller Method Parameters 360 Selecting Valid Return Types for Controller Methods 368 ftoc.indd 13 11-02-2014 08:39:54
xiv CONTENTS Using Spring Framework’s Model and View Pattern 370 Using Explicit Views and View Names 371 Using Implicit Views with Model Attributes 373 Returning Response Entities 375 Making Your Life Easier with Form Objects 380 Adding the Form Object to Your Model 381 Using the Spring Framework <form> Tags 381 Obtaining Submitted Form Data 383 Updating the Customer Support Application 384 Enabling Multipart Support 384 Converting Servlets to Spring MVC Controllers 385 Creating a Custom Downloading View 386 Summary 387 ChaPter 14: usIng servICes and rePosItorIes to suPPort Your Controllers 389 Understanding Model-View-Controller Plus Controller-Service- Repository 390 Recognizing Different Types of Program Logic 391 Repositories Provide Persistence Logic 392 Services Provide Business Logic 392 Controllers Provide User Interface Logic 393 Using the Root Application Context Instead of a Web Application Context 394 Reusing the Root Application Context for Multiple User Interfaces 394 Moving Your Business Logic from Controllers to Services 396 Using Repositories for Data Storage 399 Improving Services with Asynchronous and Scheduled Execution 404 Understanding Executors and Schedulers 404 Configuring a Scheduler and Asynchronous Support 405 Creating and Using @Async Methods 407 Creating and Using @Scheduled Methods 408 Applying Logic Layer Separation to WebSockets 409 Adding Container-Managed Objects to the Spring Application Context 409 Using the Spring WebSocket Configurator 411 Remember: A WebSocket Is Just Another Interface for Business Logic 412 Summary 416 ftoc.indd 14 11-02-2014 08:39:54
xv CONTENTS ChaPter 15: InternatIonalIzIng Your aPPlICatIon WIth sPrIng frameWork I18n 417 Why Do You Need Spring Framework i18n? 418 Making Internationalization Easier 418 Localizing Error Messages Directly 418 Using the Basic Internationalization and Localization APIs 419 Understanding Resource Bundles and Message Formats 419 Message Sources to the Rescue 421 Using Message Sources to Internationalize JSPs 422 Configuring Internationalization in Spring Framework 424 Creating a Message Source 424 Understanding Locale Resolvers 425 Using a Handler Interceptor to Change Locales 427 Providing a User Profile Locale Setting 428 Including Time Zone Support 429 Understanding How Themes Can Improve Internationalization 429 Internationalizing Your Code 430 Using the <spring:message> Tag 431 Handling Application Errors Cleanly 433 Updating the Customer Support Application 436 Using the Message Source Directly 437 Summary 440 ChaPter 16: usIng Jsr 349, sPrIng frameWork, and hIbernate valIdator for bean valIdatIon 441 What Is Bean Validation? 442 Why Hibernate Validator? 444 Understanding the Annotation Metadata Model 444 Using Bean Validation with Spring Framework 445 Configuring Validation in the Spring Framework Container 445 Configuring the Spring Validator Bean 446 Setting Up Error Code Localization 448 Using a Method Validation Bean Post-Processor 449 Making Spring MVC Use the Same Validation Beans 450 Adding Constraint Validation Annotations to Your Beans 450 ftoc.indd 15 11-02-2014 08:39:54
xvi CONTENTS Understanding the Built-in Constraint Annotations 451 Understanding Common Constraint Attributes 452 Putting Constraints to Use 452 Using @Valid for Recursive Validation 454 Using Validation Groups 455 Checking Constraint Legality at Compile-Time 457 Configuring Spring Beans for Method Validation 458 Annotating Interfaces, Not Implementations 458 Using Constraints and Recursive Validation on Method Parameters 459 Validating Method Return Values 459 Indicating That a Class Is Eligible for Method Validation 460 Using Parameter Validation in Spring MVC Controllers 462 Displaying Validation Errors to the User 463 Writing Your Own Validation Constraints 466 Inheriting Other Constraints in a Custom Constraint 466 Creating a Constraint Validator 467 Understanding the Constraint Validator Life Cycle 469 Integrating Validation in the Customer Support Application 470 Summary 472 ChaPter 17: CreatIng restful and soaP Web servICes 473 Understanding Web Services 474 In the Beginning There Was SOAP 475 RESTful Web Services Provide a Simpler Approach 476 Configuring RESTful Web Services with Spring MVC 484 Segregating Controllers with Stereotype Annotations 484 Creating Separate Web and REST Application Contexts 485 Handling Error Conditions in RESTful Web Services 488 Mapping RESTful Requests to Controller Methods 491 Improving Discovery with an Index Endpoint 495 Testing Your Web Service Endpoints 496 Choosing a Testing Tool 497 Making Requests to Your Web Service 497 Using Spring Web Services for SOAP 500 Writing Your Contract-First XSD and WSDL 501 Adding the SOAP Dispatcher Servlet Configuration 503 Creating a SOAP Endpoint 504 Summary 508 ftoc.indd 16 11-02-2014 08:39:55
xvii CONTENTS ChaPter 18: usIng messagIng and ClusterIng for flexIbIlItY and relIabIlItY 509 Recognizing When You Need Messaging and Clustering 510 What Is Application Messaging? 510 What Is Clustering? 513 How Do Messaging and Clustering Work Together? 517 Adding Messaging Support to your Application 520 Creating Application Events 520 Subscribing to Application Events 522 Publishing Application Events 523 Making your Messaging Distributable Across a Cluster 525 Updating Your Events to Support Distribution 526 Creating and Configuring a Custom Event Multicaster 527 Using WebSockets to Send and Receive Events 529 Discovering Nodes with Multicast Packets 531 Simulating a Cluster with Multiple Deployments 533 Distributing Events with AMQP 534 Configuring an AMQP Broker 536 Creating an AMQP Multicaster 537 Running the AMQP-Enabled Application 539 Summary 540 Part III: PersIstIng data WIth JPa and hIbernate orm ChaPter 19: IntroduCIng Java PersIstenCe aPI and hIbernate orm 543 What Is Data Persistence? 543 Flat-File Entity Storage 544 Structured File Storage 544 Relational Database Systems 545 Object-Oriented Databases 546 Schema-less Database Systems 546 What Is an Object-Relational Mapper? 547 Understanding the Problem of Persisting Entities 547 O/RMs Make Entity Persistence Easier 549 JPA Provides a Standard O/RM API 550 Why Hibernate ORM? 552 A Brief Look at Hibernate ORM 552 Using Hibernate Mapping Files 552 ftoc.indd 17 11-02-2014 08:39:55
xviii CONTENTS Understanding the Session API 554 Getting a Session from the SessionFactory 556 Creating a SessionFactory with Spring Framework 557 Preparing a Relational Database 559 Installing MySQL and MySQL Workbench 559 Installing the MySQL JDBC Driver 562 Creating a Connection Resource in Tomcat 563 A Note About Maven Dependencies 564 Summary 564 ChaPter 20: maPPIng entItIes to tables WIth JPa annotatIons 565 Getting Started with Simple Entities 566 Marking an Entity and Mapping It to a Table 567 Indicating How JPA Uses Entity Fields 569 Mapping Surrogate Keys 570 Using Basic Data Types 576 Specifying Column Names and Other Details 579 Creating and Using a Persistence Unit 581 Designing the Database Tables 581 Understanding Persistence Unit Scope 583 Creating the Persistence Configuration 584 Using the Persistence API 586 Mapping Complex Data Types 590 Using Enums as Entity Properties 590 Understanding How JPA Handles Dates and Times 592 Mapping Large Properties to CLOBs and BLOBs 594 Summary 596 ChaPter 21: usIng JPa In sPrIng frameWork rePosItorIes 597 Using Spring Repositories and Transactions 598 Understanding Transaction Scope 598 Using Threads for Transactions and Entity Managers 599 Taking Advantage of Exception Translation 601 Configuring Persistence in Spring Framework 602 Looking Up a Data Source 602 Creating a Persistence Unit in Code 603 Setting Up Transaction Management 607 Creating and Using JPA Repositories 610 Injecting the Persistence Unit 610 Implementing Standard CRUD Operations 611 ftoc.indd 18 11-02-2014 08:39:55