Spring by sample

Embed Size (px)

Citation preview

  • 8/13/2019 Spring by sample

    1/169

    20120607 Copyright 2004-12, LearningPatterns Inc. All rights reserved i

    Table of Contents Fast Track toSpring 3 and Hibernate

    Fast Track to Spring 3 and Hibernate ______________________________________ 1 Workshop Overview _______________________________________________________________ 2 Workshop Objectives ______________________________________________________________ 3 Workshop Agenda_________________________________________________________________ 4 Typographic Conventions ___________________________________________________________ 5 Labs ____________________________________________________________________________ 6 Release Level_____________________________________________________________________ 7

    Session 1: Introduction to Spring __________________________________________ 8 Lesson Objectives _________________________________________________________________ 9

    Overview _________________________________________________________________ 10 The Challenge of Enterprise Applications______________________________________________ 11 Shortcomings of Java/Java EE ______________________________________________________ 12 What is Spring? __________________________________________________________________ 13 The Spring Modules ______________________________________________________________ 14 The Spring Distribution____________________________________________________________ 15 The Spring Distribution____________________________________________________________ 16

    Lab 1.1 Setting Up the Environment ____________________________________________ 17

    Spring Introduction ________________________________________________________ 39 Managing Beans _________________________________________________________________ 40 A Basic Spring Application_________________________________________________________ 41 Some Bean Classes _______________________________________________________________ 42 Configuration Metadata____________________________________________________________ 43 Declaring Beans__________________________________________________________________ 44 The Spring Container _____________________________________________________________ 45

    Working With Spring _____________________________________________________________ 46 A Simple Spring Example __________________________________________________________ 47 Why Bother? ____________________________________________________________________ 48 Some BeanFactory Methods ________________________________________________________ 49

    Lab 1.2 Hello Spring World____________________________________________________ 50

    Dependencies and Dependency Injection _______________________________________ 55 Dependencies Between Objects______________________________________________________ 56 Example of a Direct Dependency ____________________________________________________ 57 Dependency Inversion Principal _____________________________________________________ 58 Example of Dependency Inversion ___________________________________________________ 59 Example of Dependency Inversion ___________________________________________________ 60 Dependency Injection (DI) in Spring _________________________________________________ 61 Dependency Injection Configuration__________________________________________________ 62 Dependency Injection Example______________________________________________________ 63 Advantages of Dependency Injection _________________________________________________ 64 Dependency Injection Reduces Coupling ______________________________________________ 65

    Lab 1.3 Dependency Injection __________________________________________________ 66 Review Questions ________________________________________________________________ 71 Lesson Summary_________________________________________________________________ 72 Lesson Summary_________________________________________________________________ 73

    Session 2: More About Bean Properties ____________________________________ 74 Lesson Objectives ________________________________________________________________ 75

  • 8/13/2019 Spring by sample

    2/169

    20120607 Copyright 2004-12, LearningPatterns Inc. All rights reserved ii

    Working with Properties ____________________________________________________ 76 Configuring Value Based Properties __________________________________________________ 77 Using Value Based Properties _______________________________________________________ 78 Property Conversions _____________________________________________________________ 79 Constructor Injection______________________________________________________________ 80 Constructor Argument Resolution____________________________________________________ 81

    Constructor Argument Resolution____________________________________________________ 82 Constructor Argument Resolution____________________________________________________ 83 Setter Injection vs. Constructor Injection ______________________________________________ 84 Setter Injection vs. Constructor Injection ______________________________________________ 85

    Lab 2.1 Spring Configuration __________________________________________________ 86

    Collection Valued Properties _________________________________________________ 96 Working with Collections __________________________________________________________ 97 Collection Property Example________________________________________________________ 98 Configuring and Properties _______________________________________________ 99 Configuring Collection of Bean References ___________________________________________ 100 Map Valued Properties ___________________________________________________________ 101

    java.util.Properties Valued Properties ________________________________________________ 102 Lab 2.2 Collection Valued Properties ___________________________________________ 103

    Additional Capabilities_____________________________________________________ 107 - Factory Methods - ______________________________________________________________ 108 Instance Factory Methods _________________________________________________________ 109 - Bean Aliases - _________________________________________________________________ 110 - Bean Definition Inheritance - _____________________________________________________ 111 Inheritance Example _____________________________________________________________ 112 - Autowiring - __________________________________________________________________ 113 Autowiring byName Example ______________________________________________________ 114 Autowiring byType ______________________________________________________________ 115 Pros and Cons of Autowiring ______________________________________________________ 116 To Autowire or Not to Autowire ____________________________________________________ 117 Review Questions _______________________________________________________________ 118 Lesson Summary________________________________________________________________ 119 Lesson Summary________________________________________________________________ 120

    Session 3: The Spring Container and API _________________________________ 121 Lesson Objectives _______________________________________________________________ 122

    ApplicationContext________________________________________________________ 123 ApplicationContext Interface ______________________________________________________ 124 ApplicationContext Implementations ________________________________________________ 125 Constructors____________________________________________________________________ 126 Using an ApplicationContext ______________________________________________________ 127 Spring Resource Access __________________________________________________________ 128 Built-in Resource Implementations__________________________________________________ 129

    Lab 3.1 Working with ApplicationContexts______________________________________ 130

    Bean Scope and Lifecycle___________________________________________________ 135 Bean Scope ____________________________________________________________________ 136 Specifying Bean Scope ___________________________________________________________ 137 Inner Beans ____________________________________________________________________ 138 Compound Names _______________________________________________________________ 139 Depends On ____________________________________________________________________ 140 Bean Creation Lifecycle __________________________________________________________ 141 Bean Creation Lifecycle Details ____________________________________________________ 142 Using the Lifecycle Interfaces for Beans______________________________________________ 143 Bean Destruction Lifecycle ________________________________________________________ 144

  • 8/13/2019 Spring by sample

    3/169

    20120607 Copyright 2004-12, LearningPatterns Inc. All rights reserved iii

    BeanPostProcessor ______________________________________________________________ 145 @PostConstruct and @PreDestroy __________________________________________________ 146 Event Handling _________________________________________________________________ 147

    Lab 3.2 Bean Lifecycle _______________________________________________________ 148

    MessageSources___________________________________________________________ 154 Issues with Messages_____________________________________________________________ 155 Resource Bundles _______________________________________________________________ 156 Defining Resource Bundles________________________________________________________ 157 Using Resource Bundles and MessageSource__________________________________________ 158 Localization / Internationalization___________________________________________________ 159 Parameterizing Messages _________________________________________________________ 160

    Lab 3.3 MessageSources______________________________________________________ 161

    Annotation Driven Configuration____________________________________________ 167 Annotations in Spring ____________________________________________________________ 168 Enabling Spring Annotations_______________________________________________________ 169 @Component and Auto-Detecting Beans _____________________________________________ 170 DI Using @Resource_____________________________________________________________ 171 Complete Declarations Using Annotations ____________________________________________ 172 Other Stereotype Annotations ______________________________________________________ 173 @Resource - Additional Uses ______________________________________________________ 174 @Autowired ___________________________________________________________________ 175 @Autowired Examples ___________________________________________________________ 176 Qualifiers______________________________________________________________________ 177 Lifecycle Annotations ____________________________________________________________ 178 XML Config - Annotations and Scanning_____________________________________________ 179 Annotation Configuration - Pro / Con ________________________________________________ 180 A Note on the XML Configuration __________________________________________________ 181 A Brief Note on Annotations_______________________________________________________ 182 Annotation Definition Example_____________________________________________________ 183

    Lab 3.4 Spring Annotations___________________________________________________ 184

    Other Capabilities_________________________________________________________ 191

    - SpEL: Spring Expression Language - _______________________________________________ 192 Other SpEL Capabilities __________________________________________________________ 193 - Validation - ___________________________________________________________________ 194 Using Validation ________________________________________________________________ 195 Configuring Validation ___________________________________________________________ 196 Validation Constraints____________________________________________________________ 197 Additional Capabilities ___________________________________________________________ 198 Review Questions _______________________________________________________________ 199 Lesson Summary________________________________________________________________ 200 Lesson Summary________________________________________________________________ 201 Lesson Summary________________________________________________________________ 202

    Session 4: Database Access With Spring __________________________________ 203 Lesson Objectives _______________________________________________________________ 204

    Issues With JDBC _________________________________________________________ 205 Problems Using JDBC Directly_____________________________________________________ 206 Let's Review Some Simple JDBC Usage _____________________________________________ 207 Simple Query on the Database _____________________________________________________ 208 Problems with the Previous Approach _______________________________________________ 209 Spring Support for the DAO Pattern _________________________________________________ 210

    Spring DAO Support ______________________________________________________ 211 The Spring Database API _________________________________________________________ 212

  • 8/13/2019 Spring by sample

    4/169

    20120607 Copyright 2004-12, LearningPatterns Inc. All rights reserved iv

    The JdbcTemplate Class __________________________________________________________ 213 The JdbcDaoSupport Class ________________________________________________________ 214 DataSources____________________________________________________________________ 215 Spring Jdbc Exception Hierarchy ___________________________________________________ 216 DAO Based on Spring Classes _____________________________________________________ 217 An Example of Using JdbcDaoSupport_______________________________________________ 218 Configuring a DataSource _________________________________________________________ 219 Example Using the DAO__________________________________________________________ 220 Looking up a DataSource in JNDI___________________________________________________ 221 Building a DAO Without the Support Class ___________________________________________ 222

    Lab 4.1 Spring JDBC ________________________________________________________ 223

    Queries and Updates_______________________________________________________ 231 Querying With JdbcTemplate ______________________________________________________ 232 Example Using queryForInt() ______________________________________________________ 233 Mapping Result Rows to Objects ___________________________________________________ 234 Defining a RowMapper Class ______________________________________________________ 235 Query Example Using a Row Mapper________________________________________________ 236 Example Using the DAO__________________________________________________________ 237 Inserting/Updating_______________________________________________________________ 238 Another Insert Example___________________________________________________________ 239 Other Kinds of Query Methods _____________________________________________________ 240 The SimpleJdbcTemplate Class_____________________________________________________ 241

    Lab 4.2 Querying ___________________________________________________________ 242 Review Questions _______________________________________________________________ 249 Lesson Summary________________________________________________________________ 250 Lesson Summary________________________________________________________________ 251

    Session 5: Introduction to Hibernate _____________________________________ 252 Lesson Objectives _______________________________________________________________ 253

    Hibernate Overview _______________________________________________________ 254 The Issues with Persistence Layers __________________________________________________ 255 Object-Relational Mapping (ORM) Issues ____________________________________________ 256 Issues with JDBC Alone __________________________________________________________ 257 Hibernate Overview______________________________________________________________ 258 Hibernate Benefits_______________________________________________________________ 259 Hibernate Environments __________________________________________________________ 260 Hibernate Architecture ___________________________________________________________ 261 More Detailed Architecture________________________________________________________ 262 More Detailed Architecture________________________________________________________ 263

    Using Hibernate __________________________________________________________ 264 Acquiring Hibernate _____________________________________________________________ 265 Using Hibernate_________________________________________________________________ 266 Configuring Hibernate____________________________________________________________ 267 Sample hibernate.cfg.xml _________________________________________________________ 268 hibernate.cfg.xml Elements ________________________________________________________ 269 SessionFactory Configuration ______________________________________________________ 270 SessionFactory Configuration Properties _____________________________________________ 271 Example Properties for PostgresSQL ________________________________________________ 272 The Configuration Class __________________________________________________________ 273 The SessionFactory Interface ______________________________________________________ 274 SessionFactory API ______________________________________________________________ 275 The Session Interface ____________________________________________________________ 276 Sessions and Transactions _________________________________________________________ 277 A Basic Hibernate Program Example ________________________________________________ 278

  • 8/13/2019 Spring by sample

    5/169

    20120607 Copyright 2004-12, LearningPatterns Inc. All rights reserved v

    Lab 5.1 Setting up Hibernate__________________________________________________ 279

    Mapping a Simple Class____________________________________________________ 290 Persistent Entity Classes __________________________________________________________ 291 Persistent Classes________________________________________________________________ 292 An Example Persistent Class_______________________________________________________ 293 The Event Class_________________________________________________________________ 294 The id Property _________________________________________________________________ 295 The Hibernate Mapping File _______________________________________________________ 296 The Element __________________________________________________ 297 The Element _____________________________________________________________ 298 The EVENTS Table _____________________________________________________________ 299 Mapping the id Property with __________________________________________________ 300 More About Primary Keys ________________________________________________________ 301 Generating the id Value___________________________________________________________ 302 Mapping Properties with _________________________________________________ 303 Hibernate Mapping Types _________________________________________________________ 304 Common Hibernate Type Mappings _________________________________________________ 305 Field Access or Property Access ____________________________________________________ 306 The Mapping File _______________________________________________________________ 307 Hibernate Sessions_______________________________________________________________ 308 The Session Interface ____________________________________________________________ 309 Retrieving Persistent Objects_______________________________________________________ 310

    Lab 5.2 Creating a Mapping File ______________________________________________ 311

    Logging _________________________________________________________________ 321 hibernate.show_sql ______________________________________________________________ 322 Simple Logging Facade for Java - SLF4J _____________________________________________ 323 Apache Log4J __________________________________________________________________ 324 Hibernate log4j.properties file______________________________________________________ 325 The log4j.properties file __________________________________________________________ 326 Modifying log4j.properties for Hibernate _____________________________________________ 327 Hibernate Logging Categories______________________________________________________ 328

    Lab 5.3 Controlling Hibernate Logging _________________________________________ 329 Review Questions _______________________________________________________________ 335 Lesson Summary________________________________________________________________ 336 Lesson Summary________________________________________________________________ 337

    Session 6: Spring / Hibernate Integration _________________________________ 338 Lesson Objectives _______________________________________________________________ 339

    Contextual Sessions________________________________________________________ 340 Session Propagation______________________________________________________________ 341 First Acquiring a SessionFactory Instance ___________________________________________ 342 Contextual Session ______________________________________________________________ 343 Using Contextual Sessions ________________________________________________________ 344 What is the "Current" Context______________________________________________________ 345 Contextual Session Scope _________________________________________________________ 346

    Spring / Hibernate Integration ______________________________________________ 347 Spring Support for Hibernate ______________________________________________________ 348 LocalSessionFactoryBean _________________________________________________________ 349 Spring Configuration of SessionFactory ______________________________________________ 350 Spring Free DAO________________________________________________________________ 351 HibernateTemplate ______________________________________________________________ 352 HibernateDaoSupport ____________________________________________________________ 353 Querying with HibernateTemplate __________________________________________________ 354 Other HibernateTemplate Query Examples____________________________________________ 355

  • 8/13/2019 Spring by sample

    6/169

    20120607 Copyright 2004-12, LearningPatterns Inc. All rights reserved vi

    Lab 6.1 Spring / Hibernate Integration _________________________________________ 356 Review Questions _______________________________________________________________ 362 Lesson Summary________________________________________________________________ 363

    Session 7: Updates and Queries _________________________________________ 364 Lesson Objectives _______________________________________________________________ 365

    Inserting and Updating ____________________________________________________ 366 Inserting Instances_______________________________________________________________ 367 Inserting Instance Example ________________________________________________________ 368 Modifying a Persistent Instance_____________________________________________________ 369 Deleting an Instance _____________________________________________________________ 370

    Lab 7.1 Inserting and Updating _______________________________________________ 371

    Querying and Hibernate Query Language (HQL) ______________________________ 376 Hibernate Query Language ________________________________________________________ 377 HQL Basics ____________________________________________________________________ 378 Executing a Query _______________________________________________________________ 379 Other Common Query Methods ____________________________________________________ 382 Where Clause / Restriction ________________________________________________________ 383 HQL Operators and Expressions ____________________________________________________ 384 Query Parameters _______________________________________________________________ 385 Using Query Parameters __________________________________________________________ 386

    Named Queries _________________________________________________________________ 387 Projection Queries _______________________________________________________________ 388 Projection Queries Returning Tuples_________________________________________________ 389 Additional Query Capabilities______________________________________________________ 390 Aggregate Functions _____________________________________________________________ 391

    Lab 7.2 Basic Querying ______________________________________________________ 392 Review Questions _______________________________________________________________ 399 Lesson Summary________________________________________________________________ 400

    Session 8: Transactions ________________________________________________ 402 Lesson Objectives _______________________________________________________________ 403

    Hibernate Transactions ____________________________________________________ 404 Transaction Overview ____________________________________________________________ 405 Transaction Lifecycle ____________________________________________________________ 406 Hibernate and Transactions ________________________________________________________ 407 Hibernate Transaction Demarcation _________________________________________________ 408 Working With Transactions________________________________________________________ 409 The Hibernate Transaction API_____________________________________________________ 410 Working in a Managed Environment ________________________________________________ 411

    Spring Transaction Management ____________________________________________ 413 Transaction Managers ____________________________________________________________ 414 Configuring Transaction Managers__________________________________________________ 415 Spring Transactions and Hibernate __________________________________________________ 416

    JTA Transaction Manager _________________________________________________________ 417 Spring Declarative Transaction Management __________________________________________ 418 Transactional Scope______________________________________________________________ 419 Transaction Attributes for Propagation _______________________________________________ 420 MANDATORY _________________________________________________________________ 421

    NESTED ______________________________________________________________________ 422 NEVER _______________________________________________________________________ 423 NOT_SUPPORTED _____________________________________________________________ 424 REQUIRED____________________________________________________________________ 425 REQUIRES_NEW ______________________________________________________________ 426

  • 8/13/2019 Spring by sample

    7/169

    20120607 Copyright 2004-12, LearningPatterns Inc. All rights reserved vii

    SUPPORTS ____________________________________________________________________ 427 Transaction Example_____________________________________________________________ 428 Transaction Attributes Some Choices ______________________________________________ 429 Specifying Transaction Attributes___________________________________________________ 431 Additional Transactional Attributes _________________________________________________ 433 Rolling Back and Exceptions ______________________________________________________ 434 Spring Proxies and Direct Invocation ________________________________________________ 435 Example Invoking Directly ______________________________________________________ 436

    Lab 8.1 Spring Transactions __________________________________________________ 438

    [Optional] Spring Transactions - XML Configuration__________________________ 447 Spring Transactions and AOP ______________________________________________________ 448 Defining a Pointcut ______________________________________________________________ 449 Defining Advice ________________________________________________________________ 450 Kinds of Advice_________________________________________________________________ 451 AOP XML Configuration Example__________________________________________________ 452 Specifying Advice With XML _____________________________________________________ 453 Specifying Transaction Advice With XML____________________________________________ 454 Attributes ___________________________________________________________ 455 Defining a Pointcut ______________________________________________________________ 456 Linking TX Advice With Pointcuts__________________________________________________ 457 More About Pointcut Expressions___________________________________________________ 458 Sample execution Designator Patterns _______________________________________________ 459 Other Designators Available in Spring AOP___________________________________________ 461 Sample Designator Patterns________________________________________________________ 462 Review Questions _______________________________________________________________ 463 Lesson Summary________________________________________________________________ 464

    Session 9: Lifecycle ___________________________________________________ 465 Lesson Objectives _______________________________________________________________ 466

    The Persistence Lifecycle ___________________________________________________ 467 The Persistence Lifecycle _________________________________________________________ 468 Hibernate Object States ___________________________________________________________ 469 Transient and Persistent State ______________________________________________________ 470 Detached and Removed State ______________________________________________________ 471 Hibernate Object States and Transitions ______________________________________________ 472 The Persistence Context __________________________________________________________ 473 Session / Persistence Context Lifespan _______________________________________________ 474 Session-per-request ______________________________________________________________ 475 The Persistence Context as Cache___________________________________________________ 476 Synchronization To the Database ___________________________________________________ 477 Flushing the session______________________________________________________________ 478 Flushing the Session _____________________________________________________________ 479 Persistence Context and Object Identity ______________________________________________ 480 Yes, It's Complicated_____________________________________________________________ 481

    Versioning and Optimistic Locking __________________________________________ 482 Detached Objects and Optimistic Locking ____________________________________________ 483 Using a Detached Instance ________________________________________________________ 484 Using a Detached Instance Example _________________________________________________ 485 Optimistic Locking and Versioning__________________________________________________ 486 Version Property in Java Class _____________________________________________________ 487 Version Element in Mapping File ___________________________________________________ 488 Automatic Version Maintenance____________________________________________________ 489 Optimistic Locking Example_______________________________________________________ 490 Updating a Detached Instance ______________________________________________________ 491

  • 8/13/2019 Spring by sample

    8/169

    20120607 Copyright 2004-12, LearningPatterns Inc. All rights reserved viii

    Session.saveOrUpdate() __________________________________________________________ 492 The unsaved-value Attribute _______________________________________________________ 493 Locking Objects_________________________________________________________________ 495 Common Lock Modes ____________________________________________________________ 496 Using Session.lock() Example______________________________________________________ 497

    Lab 9.1 Versioning __________________________________________________________ 498 Review Questions _______________________________________________________________ 502 Lesson Summary________________________________________________________________ 503

    Session 10: Relationships ______________________________________________ 506 Lesson Objectives _______________________________________________________________ 507

    Relationships Overview ____________________________________________________ 508 Object Relationships _____________________________________________________________ 509 Characteristics of Relationships ____________________________________________________ 510 Directionality___________________________________________________________________ 511 Characteristics of Relationships ____________________________________________________ 513

    Collections of Value Objects ________________________________________________ 514 Collections of Values ____________________________________________________________ 515 Modeling a Set of Values _________________________________________________________ 516 Mapping the Set of Values ________________________________________________________ 517 Using a Set of Values ____________________________________________________________ 518 More on the Java Collection Type___________________________________________________ 519 Using the Java Collection Types ____________________________________________________ 520 Modeling a List of Values _________________________________________________________ 521 Mapping a List of Values _________________________________________________________ 522 Sorted and Ordered Collections_____________________________________________________ 523 Collections of Components ________________________________________________________ 524 Mapping Collections of Components ________________________________________________ 525

    Lab 10.1 Mapping a Value Set_________________________________________________ 526

    Mapping Entity Relationships _______________________________________________ 530 Mappings Overview _____________________________________________________________ 531 Unidirectional Many-To-One Relationship ____________________________________________ 532

    The Table Structure Many-To-One ________________________________________________ 533 Mapping the Relationship _________________________________________________________ 534 Using the Relationship ___________________________________________________________ 535 Bidirectional One-To-Many Relationship_____________________________________________ 536 Defining the One-To-Many Relationship _____________________________________________ 537 Mapping the One-To-Many Relationship _____________________________________________ 538 More on the Inverse Side__________________________________________________________ 539 Cascading Operations ____________________________________________________________ 540 Transitive Persistence ____________________________________________________________ 541 The cascade Attribute ____________________________________________________________ 542 Cascade Choices ________________________________________________________________ 543 Choosing Cascade Options ________________________________________________________ 544

    Lab 10.2 Relationships _______________________________________________________ 545 Bidirectional One-To-One Relationship ______________________________________________ 554 Bidirectional One-To-One Relationship ______________________________________________ 555 Mapping a One-To-One Relationship ________________________________________________ 556 Many-To-Many Relationship ______________________________________________________ 557 Defining Many-To-Many Relationship _______________________________________________ 558 Mapping Many-To-Many Relationship_______________________________________________ 559 Lazy and Eager Loading __________________________________________________________ 561 Queries Across Relationships ______________________________________________________ 562 OUTER and FETCH JOIN ________________________________________________________ 563

  • 8/13/2019 Spring by sample

    9/169

  • 8/13/2019 Spring by sample

    10/169

  • 8/13/2019 Spring by sample

    11/169

    Notes:

    Copyright 2004-12 LearningPatterns Inc. All rights reserved. 120120607

    Fast Track to Spring 3 and Hibernate

    Fast Track to Spring 3 and Hibernate

    The Java Developer Education Series

    LearningPatterns Inc.

    Introduction

  • 8/13/2019 Spring by sample

    12/169

    Notes:

    Copyright 2004-12 LearningPatterns Inc. All rights reserved. 220120607

    Fast Track to Spring 3 and Hibernate

    Workshop Overview

    This is a fast-paced course covering the use of Spring 3 andHibernate 3 to build data-driven enterprise applications usingJava

    The course, at a high level, covers the following areas

    Architecture and Core features of Spring Spring Data Access Features Spring Transaction Support Hibernate Archit ecture and Features Mapping and Querying Persis tent Objects wi th Hibernate Hibernate Associations Mapping Hibernate Inheritance Mapping JPA Annotations and Hibernate

    Introduction

  • 8/13/2019 Spring by sample

    13/169

    Notes:

    Copyright 2004-12 LearningPatterns Inc. All rights reserved. 320120607

    Fast Track to Spring 3 and Hibernate

    Workshop Objectives

    At completion you should understand and be able to use the following:

    Spring capabilities : Spring Core : Understand and use Dependency Injection (DI) and the Spring

    container to manage application object lifecycles and dependencies Data Access : Program data access code using Spring's Jdbc or Hibernate

    templates and create DAOs (Data Access Objects) using its DAO support Transactions : Control transactions declaratively with Spring

    Hibernate Capabilities : Object Mapping : Create applications that use Hibernate to map persistent

    Java objects to a relational database Versioning : Use Hibernate versioning and optimistic locking Associations : Map collections and associations using Hibernate Inheritance : Model inheritance with Hibernate Query : Create and execute Hibernate queries using HQL and Criteria JPA/Annotations : Be familiar with Hibernate annotations, and know the

    relationship between Hibernate and the Java Persistence API

    Introduction

  • 8/13/2019 Spring by sample

    14/169

    Notes:

    Copyright 2004-12 LearningPatterns Inc. All rights reserved. 420120607

    Fast Track to Spring 3 and Hibernate

    Workshop Agenda

    Session 1: Introduction to Spring

    Session 2: More About Bean PropertiesSession 3: The Spring Container and APISession 4: Database Access With SpringSession 5: Introduction to HibernateSession 6: Spring / Hibernate IntegrationSession 7: Updates and QueriesSession 8: Transactions

    Session 9: Hibernate LifecycleSession 10: RelationshipsSession 11: Spring and the WebSession 12: Hibernate Additional TopicsSession 13: Hibernate and the JPA

    Introduction

  • 8/13/2019 Spring by sample

    15/169

    Notes:

    Copyright 2004-12 LearningPatterns Inc. All rights reserved. 520120607

    Fast Track to Spring 3 and Hibernate

    Typographic Conventions

    Code that is inline in the text will appear in a fixed-width codefont, such at this:JavaTeacher teacher = new JavaTeacher() Any class names, such as JavaTeacher , method names, or

    other code fragments will also appear in the same font If we want to emphasize a particular piece of code, we'll also

    bold it (and in the slide, change it's color) such as BeanFactory Filenames will be in italics, such as JavaInstructor.java We sometimes denote more info in the notes with a star *

    Lastly, longer code examples will appear in a separate code boxas shown belowpackage com.javatunes.teach;public class JavaInstructor implements Teacher {

    public void teach() { System.out.println("BeanFactories are way cool");

    }}

    * If we had additional information about a starred item in theslide, it would appear here in the notes

    We might also put other related information that generally pertains to the material in the slide

    Introduction

  • 8/13/2019 Spring by sample

    16/169

    Notes:

    Copyright 2004-12 LearningPatterns Inc. All rights reserved. 620120607

    Fast Track to Spring 3 and Hibernate

    Labs

    The workshop consists of approximately 50% discussion, 50%hands-on lab exercises, including a series of brief labs Many of the labs follow a common fictional case study -

    JavaTunes, an online music store The labs are contained directly in the course book, and have

    detailed instructions on what needs to be done

    The course includes setup zip files that contain skeleton codefor the labs Students just need to add code for the particular capabilities that

    they are working with There is also a solution zip file that contains completed lab code

    Lab slides contain an icon like the one in the upper rightcorner of this slide The end of each lab is clearly marked with a stop

    like this one to the right

    Lab

    STOP

    Introduction

  • 8/13/2019 Spring by sample

    17/169

    Notes:

    Copyright 2004-12 LearningPatterns Inc. All rights reserved. 720120607

    Fast Track to Spring 3 and Hibernate

    Release Level

    This manual has been tested with and contains instructionsfor running the labs using the following platforms:

    Java 5 or Java 6 Eclipse Java EE Edition Spring 3.0 (tested with 3.0.2) Hibernate 3.3+

    Hibernate 3.3 is bundled with Spring (see notes)

    Derby Database (Open Source DB from Apache)

    Most relatively recent similar versions of most of the softwarewill likely work

    There might be minor configuration changes

    Lab

    All labs have been tested on Microsoft Windows using the software listed above The labs should work on Unix with little modification, except for the database setup scripts,

    which are also supplied as Unix shell scripts

    We use the Hibernate version (3.3) that is bundled with Spring for ease of setup It appears possible to use a newer version of Hibernate (e.g. 3.5) with Spring, but that is

    non-trivial to do, and gives no benefit for the labs

    Introduction

  • 8/13/2019 Spring by sample

    18/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 820120607

    Fast Track to Spring 3 and Hibernate

    Session 1: Introduction to Spring

    OverviewSpring Introduction

    Dependency Injection

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    19/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 920120607

    Fast Track to Spring 3 and Hibernate

    Lesson Objectives

    Understand why we need something like the SpringFramework

    Understand what the Spring framework is, and how itsimplifies the development of enterprise applications usingJava

    Learn how Spring uses configuration information andDependency Injection (DI) to manage the beans (objects) inan application

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    20/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 1020120607

    Fast Track to Spring 3 and Hibernate

    Overview

    OverviewSpring Introduction

    Dependency Injection

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    21/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 1120120607

    Fast Track to Spring 3 and Hibernate

    The Challenge of Enterprise Applications

    Enterprise applications have many complex requirementswhich makes them difficult to write Many object types, with complex dependencies between them Persistent data to be retrieved from and stored to a data store Transactional requirements Remote (distributed) access requirements Web access requirements

    Java/Java EE (Enterprise Edition) has many capabilities tobuild these enterprise applications Java SE defines basic building blocks like Java primitives and

    core libraries like Collections Java EE defines a large suite of technologies for building

    enterprise applications - e.g. EJB and JDBC However, there are shortcomings to the Java solution

    There really is no formal definition of an enterprise applicationTypically though, some of the characteristics they have are:

    Used in a business environment, often in business-criticaldomains

    Have some form of persistent storage Have some form of remote access (Web/HTTP, Web service,

    Distributed Objects, etc) Require some measure of scalability and fault tolerance

    The definition of enterprise application is not important Many Java applications share some of the requirements that

    we are outlining here

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    22/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 1220120607

    Fast Track to Spring 3 and Hibernate

    Shortcomings of Java/Java EE

    Java/Java EE can have significant shortcomings, including:

    Basic Java has little support for managing the lifecycle ofyour objects and the dependencies between them Managing large numbers of objects requires significant effort

    The Java EE platform is quite large and requires a fairlyheavyweight application server Even if you are not using most of the capabilities of Java EE, the

    application server generally supports all of them

    Java EE has been difficult to use, and intrusive in its design For example, using Enterprise JavaBeans (EJB) required you to

    write business classes that implemented a specific API This is changing, and newer releases, such as EJB 3, are less

    intrusive

    Though rich in functionality, due to its complexity, and thecomplexity of the systems being written, Java / Java EE can havea number of shortcomings for writing these systems

    These programs are composed of many collaborating objectsand technologies, which require significant effort to manage

    There are many design guidelines to help you with managing thecollaboration of objects

    Best practices, design patterns, etc. These help you create a good design to make it easier to write

    and maintain your program However, these still require that you write the code thatmanages the collaboration of objects

    The newer Java and Java EE technologies have started to addressthe ease of use issue

    The use of Java annotations (introduced in Java 5), newversions of existing technologies (such as EJB 3), andcompletely new technologies such as JavaServer Faces (JSF)have made it significantly easier to use Java

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    23/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 1320120607

    Fast Track to Spring 3 and Hibernate

    What is Spring?

    Spring is a lightweight framework for building enterpriseapplications It is "lightweight" in the sense that it is non-intrusive in your

    programming, and allows you to use only those parts you needIt includes the following capabilities A Dependency Injection (Inversion of Control ) / container to

    manage objects and their dependencies A DAO package that abstracts JDCB and simplifies its use An ORM package providing integration with technologies such as

    Hibernate and JPA (Java Persistence API) An AOP package for doing aspect-oriented programming A Web package to integrate with Web technologies An MVC package that provides a full Model-View-Controller

    based Web framework for Web applications A security framework for authentication and authorization

    DAO stands for Data Access ObjectORM stands for Object-Relational Mapping

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    24/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 1420120607

    Fast Track to Spring 3 and Hibernate

    The Spring Modules

    Module diagram from the Spring Reference Documentation, Sec.1.2

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    25/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 1520120607

    Fast Track to Spring 3 and Hibernate

    The Spring Distribution

    The Spring home page is http://www.springsource.org/ Spring can be downloaded from this site

    The framework is distributed as a set of zip files Generally speaking, each module is packaged in its own zip

    Spring also has a large number of dependencies on othertechnologies For example, commons logging, log4j, and many others

    There is a core download which has the spring jars for all themodules, a reference manual, and API docs

    There is a dependencies download which has all the jarsspring depends on it is much larger than the basic download

    You can download the distribution fromhttp://www.springframework.org/download

    As of the Spring 2.5 release, the Spring security framework is aseparate download from the regular Spring distribution

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    26/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 1620120607

    Fast Track to Spring 3 and Hibernate

    The Spring Distribution

    Below left, you can see the directory structure of the coredistribution Below right, you can see the jars in the dist directory, and at

    bottom the contents of the docs directory

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    27/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 1720120607

    Fast Track to Spring 3 and Hibernate

    Lab 1.1 Setting Up the Environment

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    28/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 1820120607

    Fast Track to Spring 3 and Hibernate

    Lab 1.1 Set up the Environment

    Overview : In this lab, we will become familiar with the labstructure, set up our working environment, and test it to makesure it is running well The end goal is to compile and run an application that requires

    the Spring libraries

    Objectives : Become familiar with the lab structure Set up our environment

    Write and run a simple application that requires Spring

    Builds on previous labs : None

    Approximate Time : 30-40 minutes

    Lab

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    29/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 1920120607

    Fast Track to Spring 3 and Hibernate

    Information Content and Task Content

    Within a lab, information only content is presented in thenormal way the same as in the student manual pages Like these bullets at the top of the page

    Tasks that the student needs to perform are in a box with aslightly different look to help you identify them

    An example appears below

    Tasks to PerformLook at these instructions, and notice the different look of thebox as compared to that above Make a note of how it looks, as future labs will use this format

    OK Now get out your lab setup fi les ; we're ready to startworking

    Lab

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    30/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 2020120607

    Fast Track to Spring 3 and Hibernate

    Setup Environment

    Tasks to Perform

    Make sure that Spring 3.0 is installed likely in a directorysuch asC:\spring-framework-3.0.2.RELEASE If it's been installed in a different directory, you'll need to modify

    the instructions in the lab to refer to your install directory If it isn't installed, you'll need to download it (from

    http://www.springframework.org/download ) and unzip it

    Make sure that you have Java (version 5 or later) installed Java 6 is most likely installed in a directory like

    C:\Program Files\Java\jdk1.6.0_nn If not, you'll need to install it It can be downloaded from:http://java.sun.com/javase/downloads

    Lab

    You will need Java 5 or later for this course, as Spring 3 depends on Java 5 annotations Earlier versions of Spring were usable with older Java versions, but Spring 3 added a

    dependency on Java 5 In general, Java 5 is becoming more of a requirement, as frameworks adopt its technologies

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    31/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 2120120607

    Fast Track to Spring 3 and Hibernate

    Extract the Lab Setup Zip File

    To set up the labs, you'll need the course setup zip file * It has a name like:

    LabSetup_Spring3-Hibernate_Eclipse_20120607.zip

    Our base working directory for this course will be :C:\StudentWork\Spring This directory will be created when we extract the Setup zip It includes a directory structure and files (e.g., Java files, XML

    files, other files) that will be needed in the labs All instructions assume that this zip file is extracted to C:\. If

    you choose a different directory, please adjust accordingly

    Lab

    Tasks to PerformUnzip the lab setup file to C:\ This will create the directory structure, described in the next slide,

    containing files that you will need for doing the labs

    The setup file may be present on your computer already, or givento you by your instructor

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    32/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 2220120607

    Fast Track to Spring 3 and Hibernate

    Lab Directory Structure

    StudentWork\Spring\workspace willcontain the following folders: common : shared files LabNN : Directory for Lab NN LabNN/bin/ : compiled code (we use

    this to be Eclipse compatible) LabNN/src/ : Java source

    StudentWork\Spring contains Derby : Database files LabSetup : files needed for lab work

    LabNN : directory for any lab withadditional setup files

    Resources : Extra files (e.g. docs)

    Lab

    To make it easier to open command windows in the lab dirs, we've included a utility in thesetup that allows you to right click on a folder to open a command prompt in it To install this:

    Go to the Resources/CommandPromptHere folder Right click on the .reg file there, and select Merge Once you've done that, right clicking on a folder will show a Command Prompt Here

    selection in the context menu - Select that to open a command prompt in the directory

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    33/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 2320120607

    Fast Track to Spring 3 and Hibernate

    General Instructions

    The root lab directory where you will do your work for this labis: C:\StudentWork\Spring\workspace\Lab01.1 This directory already exists in your workspace you'll

    need to edit files under this directory, and build theapplication from within this directory

    In general, all the files you will work on for a lab will beunder the root directory (and instructions are given relativeto this directory)

    Detailed instructions are included in this lab They include complete instructions for working in the Eclipse

    environment, as well as details about the lab requirements

    Subsequent labs require you to do the same thing as this labto build/run, so they include fewer detailed instructions on howto do so

    Lab

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    34/169

  • 8/13/2019 Spring by sample

    35/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 2520120607

    Fast Track to Spring 3 and Hibernate

    Launch Eclipse

    Tasks to PerformTo launch eclipse, go to c:\eclipse and run eclipse.exe A dialog box should appear prompting for workbench location Set the workbench location to C:\StudentWork\Spring\workspace If a different default Workbench location is set, change it Click OK

    Lab

    If Eclipse was installed elsewhere, adjust the paths to the Eclipse executable accordingly You can put a shortcut to this executable on your desktop

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    36/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 2620120607

    Fast Track to Spring 3 and Hibernate

    Workbench and Java Perspective

    Tasks to Perform

    Close the welcome screen (Click the X - see notes)You should be in a Java EE perspective *If in a Java EE perspective, open a Java one by clickingthe Perspective icon at the top right of the Workbench,and select Java (as shown below left) Close the Java EE perspective by right clicking its

    icon, and selecting close (as shown below right) If you were in a Java perspective, then just remain in it

    Lab

    The Eclipse Java EE version opens in the Java EE perspective by default

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    37/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 2720120607

    Fast Track to Spring 3 and Hibernate

    Unclutter the Workbench

    Tasks to PerformLet's unclutter the Java Perspective by closing some views Close the Task List, Outline and Hierarchy views (click on the X) Open the Navigator View ( Window | Show View | Navigator ) You can save this as the default if you want (see note)

    Lab

    To save the perspective as the default Java perspective go to Window Save Perspective As Java

    You can reset the perspective to it's defaults via Window Reset Perspective

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    38/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 2820120607

    Fast Track to Spring 3 and Hibernate

    Create User Libraries

    We'll need to include a number of Spring jars in our classpath We'll set these up as a user library for ease of use

    Tasks to PerformGo to Window | Preferences | Java | Build Path | User Libraries Click New , in the next dialog, call the library Spring , and press OK Click Add External JARs , browse to \dist *, select

    (org.springframework.)beans-*.jar, core-*.jar and click Open (see notes)

    Select the Spring library again, click Add External JARs again,and browse to \projects\spring-build\lib\ivy

    Add in commons-logging.jar (which the core container depends on)Select the Spring library again, click Add JARs , and browse toworkspace\common\lib Add in the log4j jar file (see notes) Those are all the jars you need for the core functionality

    Click OK to finish creating the libarary

    Lab

    stands for the directory that Spring is installed in For example, C:\spring-framework-3.0.2.RELEASE

    The jar files in the dist dir have names like org.springframework.beans-3.0.2.RELEASE.jar Since the names are long, and will change with each release, we just abbreviate these as

    beans-*.jar in the labs leaving out the org.springframework prefix, and the release suffixIn previous releases there was a single jar (spring.jar ) containing the complete Springdistribution - that is no longer available in Spring 3

    For the labs that use the core capabilities in this section and the next section, the jar filesthat are needed are the core and beans jars, so we add in those

    Spring uses commons-logging by default, so there is at least a known logging implementationthat is always available

    However, we will use log4j which many people are familiar with, which is done by justadding in the log4j jar to the classpath, which we supply for you for ease of use

    Note that we supply the one that is distributed with the Spring dependencies download,which is why it has a name other than the simple log4j.jar

    Note - you can select multiple files by holding down the Control key as you select each file

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    39/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 2920120607

    Fast Track to Spring 3 and Hibernate

    Create a Project for our Application

    Tasks to PerformClose any open welcome screensCreate a Java Project (File |New | Java Project ) Call the project Lab01.1 Eclipse will then automatically set

    the project directory to Lab01.1 This is an existing directory with

    starter files for this lab We supply a Lab05.1 directory,

    and Eclipse will configure theproject based on its source files

    Click Next This will bring you to a dialog

    where you can set the JavaSettings for the project

    Lab

    To create a new Java Project, use the menuitem File| New | Java Project

    There are many other ways to create a project You can use the new icon on the left hand side of the toolbar, as shown above

    You will need to create a new Java project in Eclipse each time the lab instructions tell you touse a new Lab directory

    This happens several times in the course, and you'll need to create a new project each time

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    40/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 3020120607

    Fast Track to Spring 3 and Hibernate

    Add the Spring Library to the ClassPath

    Tasks to Perform

    In the Java Settings dialog, click the Libraries tab * Click the Add Library button, and in the dialog that comes up,

    select User Library then click Next Check off Spring , then click Finish in all open dialogs *

    Lab

    If you forget to add the library in this step, you can always add it later as follows Right click on the project, select Properties, then select Java Build Path Go to the Libraries tab, and add in the Spring library as described above

    When the project is created, Eclipse will attempt to compile all the Java source This will lead to warnings about unused imports, variables, etc. You can just ignore these most of them are because the files we give you are just

    skeletons, and not complete. If you want, you can shut these warnings off as follows:

    Window | Preferences | Java | Compiler | Errors/Warnings Go to the "Unnecessary Code" section, and change the settings for "Unused import",

    "Unused local or private member", and "Local variable is never read" to "Ignore"

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    41/169

  • 8/13/2019 Spring by sample

    42/169

  • 8/13/2019 Spring by sample

    43/169

  • 8/13/2019 Spring by sample

    44/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 3420120607

    Fast Track to Spring 3 and Hibernate

    The Eclipse Paradigm

    Eclipse products have two fundamental layers The Workspace files, packages, projects, resource

    connections, configuration properties The Workbench editors, views, and perspectives

    The Workbench sits on top of the Workspace and providesvisual artifacts that allow you to access and manipulatevarious aspects of the underlying resources, such as: Editor A component that allows a developer to interact with

    and modify the contents of a file.

    View A component that exposes meta-data about thecurrently selected resource.

    Perspective A grouping of related editors and views that arerelevant to a particular task and/or role.

    You can have multiple perspectives open to provide access todifferent aspects of the underlying resources

    Lab

    The physical directory structure for the Workspace can be found in the workspace directory The default location is directly under the Eclipse home directory You can specify a different workspace location when you start Eclipse

    It is even possible to set up multiple workspaces (with corresponding Workbenchs). Simplycreate a folder to house the additional workspace, and write a script that uses the Eclipseexecutable file and supplies the data argument with the location of the workspace directory toload:

    c:\eclipse\eclipse.exe -data other_workspace_folder A Perspective is basically a collection of views that are focused on a given task

    They provide different tools to work with the resources For example, the debugging perspective has views open for debugging, such as: Active

    Threads, Variables, Breakpoints, etc. There are perspectives for Java development (Java Perspective), and so on What perspectives are available depends on what version of Eclipse you have, and what

    plugins you have installed

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    45/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 3520120607

    Fast Track to Spring 3 and Hibernate

    Workbench and Workspace

    Workspace(Model)

    Workbench (View)

    Lab

    We use the terms Model and View here in the same sense as whentalking about Model-View-Controller (MVC)

    The Model is the actual data (the files) The View is the Eclipse Workbench

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    46/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 3620120607

    Fast Track to Spring 3 and Hibernate

    Navigator ViewShows how different resourcesare structured

    There are three kinds of resources: Files

    Correspond to files on thefile system

    Folders Like directories on the file system

    Projects Used to organize all yourresources and for version control.

    When you create a new project, you assign a physical location for it onthe file system. A third-party SCM (Source Control Manager) may be used to properlyshare project files amongst developers.

    Lab

    The Navigator view is one of the most commonly used views. It provides a file-based organization of the various resources. Thereare other views that give application-based, and project-basedorganization of data

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    47/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 3720120607

    Fast Track to Spring 3 and Hibernate

    Package Explorer

    The Package Explorer view, is shownby default in the Java perspective It shows the Java element hierarchy of

    the Java projects in your workbench It provides a Java-specific view of

    the resources shown in the Navigator It also makes it easy to work with Java

    resources for example to create anew class, just click on the packageyou want and select New | Class *

    Lab

    Similarly, if you wanted to create a new JSP file, you could clickon the JSP folder and select New | File

    Then name the file with a .jsp extensionIf you wanted to create a new folder under WebContent, youcould just right click on the WebContent folder and select New |Folder

    For example, we'll need to do this in one of the later labs tocreate a WebContent\js folder, and then a file underneath the js folder

    Lab 1.1: Setting Up the Environment

  • 8/13/2019 Spring by sample

    48/169

  • 8/13/2019 Spring by sample

    49/169

  • 8/13/2019 Spring by sample

    50/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 4020120607

    Fast Track to Spring 3 and Hibernate

    Managing Beans

    Managing application objects is a core Spring capability

    These managed objects are called beans A bean is just a POJO (Plain Old Java Object) Spring borrowed this terminology from JavaBeans and EJB

    Spring uses a container , the Dependency Injection (DI) orInversion of Contro l (IoC ) container, to manage objects Configuration metadata is supplied to the container so it knows

    how to instantiate, conf igure, and assemble your beans Generally, this configuration data is in a simple XML format

    You use the configuration metadata to provide beandefinitions and dependencies to the container The container then does all the work of managing the beans

    We'll cover the Spring container, and the principles behind it, in more detail later For now, we will just describe some of its basic capabilities

    Configuration metadata can also be provided in the Java properties format, or even provided programmatically (using Spring's public API)

    These are generally more cumbersome to use, and we won't cover them in this course The vast majority of Spring users use the XML format In fact, the Spring IoC container is totally decoupled from the external form of the metadata It has its own internal format which it uses to store this information

    We mostly only cover the XML format in this courseSpring 2.x also added a number of Java 5 annotations that can be used

    We'll cover the most important annotationsSpring will create and initialize bean instances based on your configuration data

    You can then request those instances from the Spring container by name We'll see how this works soon

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    51/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 4120120607

    Fast Track to Spring 3 and Hibernate

    A Basic Spring Application

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    52/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 4220120607

    Fast Track to Spring 3 and Hibernate

    Some Bean Classes

    Let's say we had the following types (your business objects) An interface, Teacher , defining the functionality we want to use A concrete class, JavaInstructor , which implemented this

    interface, and provided the functionality Note that Spring strongly advocates the concept of programming

    to interfaces (see notes)

    Let's look at how to manage them using Spring

    package com.javatunes.teach;public interface Teacher {

    public void teach ();}

    package com.javatunes.teach;public class JavaInstructor implements Teacher {

    public void teach () { System.out.println("BeanFactories are way cool");

    }}

    Programming to interfaces provides many advantages bydecoupling your code from concrete implementation classes

    This is not a concept unique to Spring Many design patterns are based on the decoupling gained by

    programming to an interface We'll soon see how the Spring framework makes these

    advantages even more usable and powerful by helpingmanage the dependencies that have been abstracted usinginterfaces

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    53/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 4320120607

    Fast Track to Spring 3 and Hibernate

    Configuration Metadata

    A Spring configuration contains bean definitions Contain information about your beans (the metadata) Bean definitions correspond to actual objects in your application

    that the Spring container will manage Typically, there are many bean definitions and dependencies

    Beans are configured with a top level element It contains namespace declarations (for Spring 3 in the example)

    and elements as shown in the beans.xml file below

    Spring 2.0 and later provided an XML Schema for the XML configuration file The examples and lab setup files have the necessary XML syntax in them to refer to the

    Spring XML Schema properly This is standard XML usage, and we don't go into the details here of how to use an XML

    Schema Refer to an XML reference if you need more detail on this

    The XML Schema is now the recommended way to use Spring, and we'll use it in this course Earlier versions of Spring used a DTD to describe the XML configuration file

    Typically you'll configure beans such as Service layer objects, DAO objects, Hibernate session factories, JMS queue references

    Some BeanFactory implementations also permit the registration of existing objects that have been created outside the factory (by user code)The schemaLocation property shown in the slide is for Spring 3.0

    For Spring 2.0/2.5, you would use spring-beans-2.0.xsd or 2.5.xsd rather than spring-beans-3.0.xsd in the schemaLocation property

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    54/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 4420120607

    Fast Track to Spring 3 and Hibernate

    Declaring Beans

    Each bean definition must specify a package-qualified classname for the bean Usually the actual implementation class of the bean (i.e. the

    class that the container will instantiate) In our example, the class attribute, specifies the implementation

    as com.javatunes.teach.JavaInstructor

    In general, a bean identifier (or name) is also specified In our example, we used the id attribute, to specify the identifier

    as springGuru Serves as a label for the bean both in code and the config file A bean can have multiple names (or aliases) Generally, bean names use camelCase as the convention for

    bean names (e.g. springGuru)

    There are more sophisticated ways to create beans, for example with a factory class, in whichcase the class name may not be the actual implementation classIf you don't specify a bean name, the container will generate a unique name for the bean

    This can be useful in some more sophisticated scenariosThe springGuru name follows the same convention as Java instance field names

    Bean names start with a lowercase letter, and are camel cased from then onBean names must be unique within the container the bean is hosted inUsually a bean will have a single name

    If it has multiple names, these are considered aliasesThe id attribute must follow the standard XML rules for ids

    There is a limited set of characters that are allowed for XML idsThe name attribute can also be used to specify (multiple) names

    You can have a value that specifies multiple bean ids separated by a comma, semicolon, orwhitespace

    If there is no id attribute, the first name becomes the identifier, the rest are aliases You may use the id and name attributes at the same time

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    55/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 4520120607

    Fast Track to Spring 3 and Hibernate

    The Spring Container

    The Spring container is represented by the interfaceorg.springframework.beans.factory.BeanFactory It provides a configuration mechanism for managing any kind of

    object Spring comes with a number of BeanFactory implementations XMLBeanFactory , the most common implementation, uses the

    XML configuration metadata we just saw

    The interface org.springframework.core.io.Resource

    is used to abstract access to resources (e.g. a config file) Often used to access the XML data to configure a BeanFactory FileSystemResource is a concrete implementation that allows

    you to easily access resources on the file system

    We'll show a simple example first, then more depth later

    Some of the responsibilities of the container are: Instantiating and configuring application objects Assembling dependencies between objects

    Spring also uses the ApplicationContext class to representthe container

    ApplicationContext extends BeanFactory , and addssome additional capabilities which we'll look at later

    The Resource interface allows you to specify paths to resourcesas resource strings

    These are then mapped by a particular implementation to theactual resource, for example a file on a file system or fromthe Java classpath

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    56/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 4620120607

    Fast Track to Spring 3 and Hibernate

    Working With Spring

    At the very highest level, a typical scenario for using Springincludes the following main steps:

    Create (XML) configuration data for your beans e.g. A file " beans.xml " containing the Spring configuration This is the cookbook that tells Spring how to create objects

    Access the configuration information in your code usingthe Spring resource classes e.g. Use FileSystemResource to access beans.xml

    Create a bean factory which gets its configuration data fromthe resource you created This creates a bean factory tailored to your beans

    Create beans using the bean factory e.g. using the BeanFactory.getBean method

    There are many, many usage scenarios for Spring And many, many different alternatives for each scenario Spring is very large, and has a lot of flexibility and capability

    In this initial introduction we show you one straightforward wayof using Spring

    We will gradually introduce more capabilities throughout thecourse

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    57/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 4720120607

    Fast Track to Spring 3 and Hibernate

    A Simple Spring Example

    The following code, along with the beans.xml configuration fileshown earlier, gives a simple example of using Spring We first instantiate a FileSystemResource to read beans.xml We next instantiate an XMLBeanFactory based on beans.xml Lastly, we ask the factory to instantiate the springGuru bean

    package com.javatunes.teach;

    import org.springframework.core.io.Resource;import org.springframework.core.io.FileSystemResource;import org.springframework.beans.factory.BeanFactory;import org.springframework.beans.factory.xml.XmlBeanFactory;

    public class TeachMeSpring { public static void main(String[] args) { Resource res = new FileSystemResource("beans.xml");BeanFactory factory = new XmlBeanFactory(res);// Note that getBean is a new Spring 3 version using genericsTeacher teacher = factory.getBean("springGuru", Teacher.class);teacher.teach(); // Use our bean

    }}

    There are many resource implementations that come with Spring Another example is the ClassPathResource which locates resources on the Java

    classpath If beans.xml was on the classpath, then you could access it with the following codeResource resource =

    new ClassPathResource ("beans.xml");

    A bean definition can be seen as a recipe for creating one or more actual objects The container looks at the recipe for a named bean when asked, and uses the configuration

    metadata encapsulated by that bean definition to create (or acquire) an actual object

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    58/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 4820120607

    Fast Track to Spring 3 and Hibernate

    Why Bother?

    The example looks like a lot of work to create a single object !

    The main benefit, in this simple example, is that we'vedecoupled our program code from a dependency on theimplementation class JavaInstructor Our code does not need to know about JavaInstructor All we know is that it provides the functionality we need (i.e.

    implements the Teacher interface) We are free to configure the program with any implementation

    we want, and our code will not change This can be very useful for complex systems

    We'll soon see additional capabilities that make Spring useful

    In this simple example, it looks like we've done quite a bit of workto instantiate a single instance of a single class

    What is the benefit?

    The decoupling we've achieved seems like a simple thing, but ithas a lot of benefits, especially when maintaining large systems

    We'll see how useful it can be when we explore more of thecapabilities

    Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    59/169

    Notes:

    Some BeanFactory Methods

    boolean containsBean(String) : returns true if BeanFactory contains a bean definition or instance with the given name

    T getBean(String, Class requiredType) : returns abean instance, registered under the given name Spring 3.0 style using Java generics (see notes) and is preferred

    Object getBean(String) : old style non generics version Requires cast

    Class getType(String name) : returns the Class of the beanwith the given name

    boolean isSingleton(String) : determines whether or not thenamed bean is a singleton String[] getAliases(String) : Return the aliases for the givenbean name, if anyThere are many more we'll look at some, but view the javadoc formore info

    getBean(String, Class) returns either a singleton (shared) instance, or newly created bean We'll look at how this is configured later NoSuchBeanDefinitionException thrown if the bean can't be found BeansException thrown if an exception occurred while instantiating/preparing the bean BeanNotOfRequiredTypeException thrown if the bean is not of the required type

    Object getBean(String) returns an object which is then cast to the required type The newer getBean(String,Class) method is generally preferred.

    getType(String) throws NoSuchBeanDefinitionException if the bean can't be found

    isSingleton(String) throws NoSuchBeanDefinitionException if bean can't be found The method T getBean(String, Class requiredType) may look strange

    The first in the return type simply indicates that this is a generic method, parameterized by the type parameter

    The T return value indicates that the return type is generic (that is, it will take on differenttypes based on the parameter)

    The Class argument indicates that when you call the method, you pass in the classwhich specifies what type actually is in that call

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 4920120607

    Fast Track to Spring 3 and Hibernate Session 1: Introduction to Spring

  • 8/13/2019 Spring by sample

    60/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 5020120607

    Fast Track to Spring 3 and Hibernate

    Lab 1.2 Hello Spring World

    Lab 1.2: Hello Spring World

  • 8/13/2019 Spring by sample

    61/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 5120120607

    Fast Track to Spring 3 and Hibernate

    Lab 1.2 Hello Spring World

    Overview : In this lab, we will write a very simple Springprogram The end goal is to build a simple Spring application and run it This lab uses the JavaInstructor , Teacher , and

    TeachMeSpring types shown previously in the student manual

    Objectives : Become familiar with the different parts of a basic Spring

    program

    Write and run a (very) simple Spring application

    Builds on previous labs : 1.1

    Approximate Time : 20-30 minutes

    Lab

    The purpose of this lab is to become familiar with the different parts of a Spring application

    Accordingly, the program is as simple as we can make it It mirrors the code already shown in the previous section

    In later labs, we'll work with more complex applications

    Lab 1.2: Hello Spring World

  • 8/13/2019 Spring by sample

    62/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 5220120607

    Fast Track to Spring 3 and Hibernate

    Writing and Configuring a Bean in Spring

    Tasks to Perform

    Continue to work in the Lab01.1 projectOpen up the JavaInstructor.java fileThe class is in the com.javatunes.teach package, whichmeans the file is in src\com\javatunes\teachMake sure that JavaInstructor implements the Teacherinterface (in file Teacher.java ) Remember that we code to interfaces to decouple us from a

    specific implementation

    Open up the src/beans.xml file Finish up the declaration of the element by declaring a

    bean with an id of springGuru , and a class ofcom.javatunes.teach.JavaInstructor

    Lab

    There are two other files in the src tree that we will use in the nextlab

    InfoSource.java and SpringCourseBook.java Ignore these for now

    Lab 1.2: Hello Spring World

  • 8/13/2019 Spring by sample

    63/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 5320120607

    Fast Track to Spring 3 and Hibernate

    Using a Bean in a Program

    Tasks to Perform

    Open up TeachMeSpring.java , look for the TODO comments,and add in the following code First, create a FileSystemResource to read src/beans.xml Next, create a BeanFactory with the resource above Next, look up the springGuru bean from the BeanFactory Finally call teach() on the springGuru bean

    Make sure you have no compilation errors in your codeRun the TeachMeSpring program again Run the same way as in previous labs You should see the output from the teach() method

    You've successfully configured and used a bean with Spring Congratulations !

    Lab

    Lab 1.2: Hello Spring World

  • 8/13/2019 Spring by sample

    64/169

    Notes:

    Copyright 2007-10 LearningPatterns Inc. All rights reserved. 5420120607

    Fast Track to Spring 3 and Hibernate

    Logging and Additional Things (Optional)

    We've provided a log4j.properties file in the src directory This configures some of the logging that Spring will do You can reduce the logging output by opening this file, and

    changing the INFO to WARN at the top line of the file:log4j.rootLogger= WARN , stdout

    You can increase the logging by using DEBUG instead

    Other things to try Try looking up the bean by a different name what happens? Try casting the bean you look up to a JavaInstructor

    instead of a Teacher Does this work? Is it a good idea?

    Change your code back to your original solutionbefore going on STOP

    Spring has logging built into it It uses commons-logging by default, which will detect the

    log4j jar file and use that if it is on the classpath You can see the logging by properly configuring it, as we do

    in the log4j.properties file The details of log4j are beyond the scope of this course

    Casting the bean you look up to a JavaInstructor will work These are POJOs, and the actual type is JavaInstructor It's not a good idea though, because you are defeating the

    purpose of decoupling your code from the actualimplementation type

    Lab 1.2: Hello Spring World

  • 8/13/2019 Spring by sample

    65/169

    Notes:

    Copyright 2007-10 Lea