Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347...

169
20120607 Copyright © 2004-12, LearningPatterns Inc. All rights reserved i Table of Contents – Fast Track to Spring 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 Evaluation Copy

Transcript of Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347...

Page 1: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

Table of Contents – Fast Track to Spring 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

Evaluation Copy

Page 2: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 <list> and <set> 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

Evaluation Copy

Page 3: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

Evaluation Copy

Page 4: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

Evaluation Copy

Page 5: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 <hibernate-mapping> Element __________________________________________________ 297 The <class> Element _____________________________________________________________ 298 The EVENTS Table _____________________________________________________________ 299 Mapping the id Property with <id> __________________________________________________ 300 More About Primary Keys ________________________________________________________ 301 Generating the id Value___________________________________________________________ 302 Mapping Properties with <property>_________________________________________________ 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

Evaluation Copy

Page 6: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

Evaluation Copy

Page 7: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 <tx:method> 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

Evaluation Copy

Page 8: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

Evaluation Copy

Page 9: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

FETCH JOIN Example ___________________________________________________________ 564 Lab 10.3 – Working With Relationships __________________________________________ 565

Mapping Inheritance ______________________________________________________ 570 Inheritance_____________________________________________________________________ 571 Entity Inheritance _______________________________________________________________ 572 Details of Entity Inheritance _______________________________________________________ 573 Single-Table Strategy ____________________________________________________________ 574 Class Definitions for Single-Table __________________________________________________ 575 Mapping for Single-Table _________________________________________________________ 576 Sample Table Entries_____________________________________________________________ 577 Single-Table: Pros and Cons _______________________________________________________ 578 Table per Subclass (Joined Subclass) ________________________________________________ 579 Mapping for Table per Subclass ____________________________________________________ 580 Sample Table Entries_____________________________________________________________ 581 Joined: Pros and Cons ____________________________________________________________ 582 Table per Concrete Class__________________________________________________________ 583

Lab 10.4 – Working With Inheritance____________________________________________ 584 Review Questions _______________________________________________________________ 589 Lesson Summary ________________________________________________________________ 591

Session 11: Spring and the Web _________________________________________ 594 Spring and Java EE ______________________________________________________________ 595

Java EE Web Applications__________________________________________________ 596 Web Application Structure ________________________________________________________ 597 Web Application Components______________________________________________________ 598 ApplicationContext and Web Apps__________________________________________________ 599 Configuring ContextLoaderListener _________________________________________________ 600 Using the Application Context _____________________________________________________ 601

Lab 11.1 – Spring and the Web _________________________________________________ 602 Session 12: Additional Hibernate Topics __________________________________ 618

Lesson Objectives _______________________________________________________________ 619 equals() and hashCode()____________________________________________________ 620

Defining equals() and hashCode()___________________________________________________ 621 Redefining equals() ______________________________________________________________ 622 Example of equals() and hashCode()_________________________________________________ 623

Caching _________________________________________________________________ 624 Second-Level Cache _____________________________________________________________ 625 Data Appropriate for Caching ______________________________________________________ 626 Cache Providers_________________________________________________________________ 627 Configuring Caching _____________________________________________________________ 628 Cache Configuration Example______________________________________________________ 629 Concurrency Strategies ___________________________________________________________ 630 Managing the Caches ____________________________________________________________ 631

Design Considerations _____________________________________________________ 632 Overview ______________________________________________________________________ 633 - Long Conversations - ___________________________________________________________ 634 Session-Per-Conversation (Extended Session) _________________________________________ 635 Session-Per-Conversation _________________________________________________________ 636 - Problems with Web Applications - _________________________________________________ 637 Open Session In View Pattern ______________________________________________________ 638 Open Session In View Example ____________________________________________________ 639 - Query Efficiency Techniques - ____________________________________________________ 640

Evaluation Copy

Page 10: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

Beware of n+1 Select Issue ________________________________________________________ 641 Prefetching Data in Batches _______________________________________________________ 642 Data Access Object (DAO) ________________________________________________________ 643

[Optional] Session 13: Hibernate and the Java Persistence API (JPA) _________ 644 Lesson Objectives _______________________________________________________________ 645

JPA Overview ____________________________________________________________ 646 Java Persistence API Overview_____________________________________________________ 647 Java Persistence Environments _____________________________________________________ 648 Hibernate and JPA_______________________________________________________________ 649

Mapping a Simple Class____________________________________________________ 650 Entity Classes __________________________________________________________________ 651 Event Entity Mapped with JPA _____________________________________________________ 652 javax.persistence.Entity Annotation _________________________________________________ 653 The Event Class_________________________________________________________________ 654 The Id Property _________________________________________________________________ 655 Mapping Properties ______________________________________________________________ 656 Basic Mapping Types ____________________________________________________________ 657

Entity Manager and Persistence Context ______________________________________ 658 The Entity Manager & Persistence Context ___________________________________________ 659 Persistence Unit_________________________________________________________________ 660 persistence.xml _________________________________________________________________ 661 persistence.xml Example__________________________________________________________ 662 Acquiring an EntityManager _______________________________________________________ 663 Working With Transactions________________________________________________________ 664 Retrieving Persistent Objects_______________________________________________________ 665

Inserts and Queries________________________________________________________ 666 Persisting a New Entity ___________________________________________________________ 667 Java Persistence Query Language ___________________________________________________ 668 Executing a Query _______________________________________________________________ 669 WHERE Clause and Query Parameters_______________________________________________ 671 Named Queries _________________________________________________________________ 672 Version Property in Java Class _____________________________________________________ 674 Versioned Class and Detached Objects _______________________________________________ 675

Relationships _____________________________________________________________ 676 JPA Support for Relationships _____________________________________________________ 677 Mapping the Many-To-One Relationship _____________________________________________ 678 Mapping the One-To-Many Relationship _____________________________________________ 679 Loading and Cascading ___________________________________________________________ 680 Queries Across Relationships ______________________________________________________ 681 Inheritance_____________________________________________________________________ 682 Entity Definitions for Single-Table __________________________________________________ 683 Entity Definitions for Joined _______________________________________________________ 684 Lesson Summary ________________________________________________________________ 685

Recap ______________________________________________________________ 686 Recap of what we've done _________________________________________________________ 687 Resources for More Learning ______________________________________________________ 688

Evaluation Copy

Page 11: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

Evaluation Copy

Page 12: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 and Hibernate 3 to build data-driven enterprise applications using Java

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

– Architecture and Core features of Spring– Spring Data Access Features– Spring Transaction Support– Hibernate Architecture and Features– Mapping and Querying Persistent Objects with Hibernate– Hibernate Associations Mapping– Hibernate Inheritance Mapping– JPA Annotations and Hibernate

Introduction

Evaluation Copy

Page 13: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

Evaluation Copy

Page 14: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

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

Fast Track to Spring 3 and Hibernate

Workshop Agenda

Session 1: Introduction to SpringSession 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: TransactionsSession 9: Hibernate LifecycleSession 10: RelationshipsSession 11: Spring and the WebSession 12: Hibernate Additional TopicsSession 13: Hibernate and the JPA

Introduction

Evaluation Copy

Page 15: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 code font, 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 box

as 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 the slide, it would appear here in the notes

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

Introduction

Evaluation Copy

Page 16: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 doneThe course includes setup zip files that contain skeleton code for 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 right corner of this slide– The end of each lab is clearly marked with a stop

like this one to the right

Lab

STOP

Introduction

Evaluation Copy

Page 17: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 instructions for 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 software will 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

Evaluation Copy

Page 18: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

Evaluation Copy

Page 19: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 Spring Framework

Understand what the Spring framework is, and how it simplifies the development of enterprise applications using Java

Learn how Spring uses configuration information and Dependency Injection (DI) to manage the beans (objects) in an application

Session 1: Introduction to Spring

Evaluation Copy

Page 20: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

Evaluation Copy

Page 21: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 requirements which 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 to build 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-critical domains

– 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

Evaluation Copy

Page 22: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 of your objects and the dependencies between them– Managing large numbers of objects requires significant effort

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

application server generally supports all of themJava 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 the complexity of the systems being written, Java / Java EE can havea number of shortcomings for writing these systems

– These programs are composed of many collaborating objects and technologies, which require significant effort to manage

There are many design guidelines to help you with managing the collaboration 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 that

manages the collaboration of objectsThe newer Java and Java EE technologies have started to address the ease of use issue

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

Session 1: Introduction to Spring

Evaluation Copy

Page 23: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 enterprise applications– 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

Evaluation Copy

Page 24: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

Evaluation Copy

Page 25: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 other technologies– For example, commons logging, log4j, and many others

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

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

You can download the distribution from http://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

Evaluation Copy

Page 26: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 core distribution– 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

Evaluation Copy

Page 27: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

Evaluation Copy

Page 28: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 lab structure, set up our working environment, and test it to make sure 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

Evaluation Copy

Page 29: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 the normal 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 a slightly different look – to help you identify themAn 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 files; we're ready to start working

Lab

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 30: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

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

Fast Track to Spring 3 and Hibernate

Setup Environment

Tasks to PerformMake sure that Spring 3.0 is installed – likely in a directory such 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 itMake 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

Evaluation Copy

Page 31: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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.zipOur 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

Evaluation Copy

Page 32: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

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

Fast Track to Spring 3 and Hibernate

Lab Directory Structure

StudentWork\Spring\workspace will contain 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 with additional 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 the setup 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

Evaluation Copy

Page 33: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 lab is: C:\StudentWork\Spring\workspace\Lab01.1– This directory already exists in your workspace – you'll

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

– In general, all the files you will work on for a lab will be under the root directory (and instructions are given relative to 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 requirementsSubsequent labs require you to do the same thing as this lab to build/run, so they include fewer detailed instructions on howto do so

Lab

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 34: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 2420120607

Fast Track to Spring 3 and Hibernate

The Eclipse Development Environment

Eclipse is an open source platform for building integrated development environments (IDEs)– Used mainly for Java development– Can be extended via plugins to create applications useful in

many areas (e.g. C# programming)– http://www.eclipse.org is the main website

The remainder of this lab gives detailed instructions on using Eclipse to run the labs– Starting it, creating and configuring projects, etc.

The other labs in the course include fewer specific details regarding Eclipse – they may just say build/run as previously– For these labs, you should use the same procedures to build/run

as in this lab– Refer back to these lab instructions as needed

Lab

The Eclipse source base was originally developed by IBM– It was released by IBM into open source– IBM's RAD (and previously its WSAD) environment is built

on top of Eclipse

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 35: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

Evaluation Copy

Page 36: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

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

Fast Track to Spring 3 and Hibernate

Workbench and Java Perspective

Tasks to PerformClose 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 clicking the 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

Evaluation Copy

Page 37: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

Evaluation Copy

Page 38: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 <spring>\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 <spring>\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 to workspace\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

<spring> 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 Spring distribution - 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 files that 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 implementation that is always available

– However, we will use log4j which many people are familiar with, which is done by just adding 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

Evaluation Copy

Page 39: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 the project based on its source files

– Click Next– This will bring you to a dialog

where you can set the Java Settings 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 to use 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

Evaluation Copy

Page 40: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 PerformIn 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

Evaluation Copy

Page 41: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 3120120607

Fast Track to Spring 3 and Hibernate

Running the Lab

Tasks to PerformWe will use Eclipse to run a skeleton program we supply in TeachMeSpring.javaAfter a clean build (one that is error-free, but not necessarily warning-free), do the following– In the Package Explorer pane,

right click on TeachMeSpring.java(in package com.javatunes.teach)

– Select:Run As -> Java Application

– This will automatically find the main method in TechMeSpringand run it for you

Lab

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 42: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 3220120607

Fast Track to Spring 3 and Hibernate

Program Output

You should see output in the Eclipse Console view showing the results of running the programNote: You will follow similar procedures whenever you have a Java program to run in the labs– The only thing that may change is the program class that you'll

need to right click on to run

Lab

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 43: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 3320120607

Fast Track to Spring 3 and Hibernate

Important Notes for Using Eclipse

Each lab that has a separate lab directory will require you to create a new Eclipse project– Sometimes several labs are done one directory, in which case

you will use the same project for all of them

Each time you create a new project, you'll need to add the Spring library to the project build path to compile and run

You should copy setup files directly into an Eclipse view -in which case a refresh is not needed– If you COPY files into a project directory via the file system (e.g.

using Windows Explorer) you need to Refresh the project• By right clicking on the project, and selecti Refresh

For anyone not familiar with Eclipse, the next few slides give a(very) brief overview of how Eclipse is structured– Nothing you need to do in those slides – they're for info only

Lab

Take note of the Lab instructions

Any lab that starts out saying that it will be done in a new directory will require you to create a new Java project

– You'll create the project with the name of the directory specified in the lab

Any lab that has you copy files from the setup to your working directory you should copy directly into the Eclipse IDE

– Otherwise, if you use the file system, Eclipse will require you to refresh the project as described above so Eclipse becomes aware of the new files.

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 44: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 provides visual artifacts that allow you to access and manipulate various 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 the

currently selected resource.– Perspective – A grouping of related editors and views that are

relevant to a particular task and/or role.You can have multiple perspectives open to provide access to different 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). Simply create a folder to house the additional workspace, and write a script that uses the Eclipse executable file and supplies the ‘data’ argument with the location of the workspace directory to load:

– c:\eclipse\eclipse.exe -data other_workspace_folderA 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

Evaluation Copy

Page 45: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 when talking 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

Evaluation Copy

Page 46: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

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

Fast Track to Spring 3 and Hibernate

Navigator View

Shows how different resources are structuredThere are three kinds of resources:– Files

• Correspond to files on the file system

– Folders• Like directories on the file system

– Projects• Used to organize all your resources and for version control.• When you create a new project, you assign a physical location for it on the file system.• A third-party SCM (Source Control Manager) may be used to properly share 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. There are other views that give application-based, and project-based organization of data

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 47: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

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

Fast Track to Spring 3 and Hibernate

Package Explorer

The Package Explorer view, is shown by 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 a new class, just click on the package you want and select New | Class *

Lab

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

– Then name the file with a .jsp extensionIf you wanted to create a new folder under WebContent, you could 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 to create a WebContent\js folder, and then a file underneath the js folder

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 48: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 3820120607

Fast Track to Spring 3 and Hibernate

Editors

There is a source editor (like this one for a .java file) for all character files. (.java, .jsp, .html, etc.)

STOP

Lab

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 49: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 3920120607

Fast Track to Spring 3 and Hibernate

Spring Introduction

OverviewSpring Introduction

Dependency Injection

Session 1: Introduction to Spring

Evaluation Copy

Page 50: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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) or Inversion of Control (IoC) container, to manage objects– Configuration metadata is supplied to the container so it knows

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

You use the configuration metadata to provide bean definitions 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

Evaluation Copy

Page 51: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

Evaluation Copy

Page 52: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 Springpackage 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 by decoupling 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 helping manage the dependencies that have been abstracted using interfaces

Session 1: Introduction to Spring

Evaluation Copy

Page 53: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 <beans> element– It contains namespace declarations (for Spring 3 in the example)

and <bean> elements as shown in the beans.xml file below

<?xml version="1.0" encoding="UTF-8"?><!-- The beans namespace is the default one for the document -->

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"/>

</beans>

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

Evaluation Copy

Page 54: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 class name 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 which case 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, or whitespace

– 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

Evaluation Copy

Page 55: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 interface org.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.Resourceis 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 represent the container– ApplicationContext extends BeanFactory, and adds

some additional capabilities which we'll look at later

The Resource interface allows you to specify paths to resources as resource strings

– These are then mapped by a particular implementation to the actual resource, for example a file on a file system or from the Java classpath

Session 1: Introduction to Spring

Evaluation Copy

Page 56: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 Spring includes 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 using the Spring resource classes– e.g. Use FileSystemResource to access beans.xml

Create a bean factory which gets its configuration data from the 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 the course

Session 1: Introduction to Spring

Evaluation Copy

Page 57: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 file shown 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

Evaluation Copy

Page 58: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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've decoupled our program code from a dependency on the implementation 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 work to instantiate a single instance of a single class

– What is the benefit?

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

– We'll see how useful it can be when we explore more of the capabilities

Session 1: Introduction to Spring

Evaluation Copy

Page 59: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Some BeanFactory Methods

boolean containsBean(String): returns true if BeanFactorycontains a bean definition or instance with the given name<T> T getBean(String, Class<T> requiredType): returns a bean instance, registered under the given name– Spring 3.0 style using Java generics (see notes) and is preferredObject getBean(String): old style – non generics version– Requires castClass getType(String name): returns the Class of the bean with the given nameboolean isSingleton(String): determines whether or not the named bean is a singletonString[] getAliases(String): Return the aliases for the given bean name, if anyThere are many more – we'll look at some, but view the javadoc for more 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 foundisSingleton(String) throws NoSuchBeanDefinitionException if bean can't be foundThe method <T> T getBean(String, Class<T> requiredType) may look strange

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

– The T return value indicates that the return type is generic (that is, it will take on different types based on the <T> parameter)

– The Class<T> argument indicates that when you call the method, you pass in the class which specifies what type <T> 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

Evaluation Copy

Page 60: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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

Evaluation Copy

Page 61: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 Spring program– 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 differentparts 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

Evaluation Copy

Page 62: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 PerformContinue to work in the Lab01.1 projectOpen up the JavaInstructor.java fileThe class is in the com.javatunes.teach package, which means the file is in src\com\javatunes\teachMake sure that JavaInstructor implements the Teacher interface (in file Teacher.java)– Remember that we code to interfaces to decouple us from a

specific implementationOpen up the src/beans.xml file– Finish up the declaration of the <bean> element by declaring a

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

Lab

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

– InfoSource.java and SpringCourseBook.java– Ignore these for now

Lab 1.2: Hello Spring World

Evaluation Copy

Page 63: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 PerformOpen 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

Evaluation Copy

Page 64: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

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 insteadOther 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 solution before 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 actual implementation type

Lab 1.2: Hello Spring World

Evaluation Copy

Page 65: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 5520120607

Fast Track to Spring 3 and Hibernate

Dependencies and Dependency Injection

OverviewSpring Introduction

Dependency Injection

Session 1: Introduction to Spring

Evaluation Copy

Page 66: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 5620120607

Fast Track to Spring 3 and Hibernate

Dependencies Between Objects

Typically, different objects work together in an OO application– e.g., Object A directly uses Object B to accomplish a goal– In that case, Object A depends on Object B

Direct dependencies like this can lead to undesirable characteristics in large / complex applications– Rigidity: Hard to make changes - they affect too many other

parts of the system– Fragility: Changes cause unexpected parts of the system to

break– Immobility: Hard to reuse functionality in another system -

modules can't be disentangled from the application

We'll show an example of a direct dependency, then show an alternative design approach that uses Dependency Inversion

In straightforward applications, Object A will often just create an instance of Object B and use it

– Object A is highly coupled to, and directly dependent on, Object B

Session 1: Introduction to Spring

Evaluation Copy

Page 67: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 5720120607

Fast Track to Spring 3 and Hibernate

Example of a Direct Dependency

Assume JavaInstructor uses a class SpringCourseBook– In the example below, JavaInstructor creates an instance of SpringCourseBook directly

– JavaInstructor depends on the details in lower level modules – If we decide that Java instructors will get the latest information

from the Spring Wiki, instead of from a SpringCourseBook, JavaInstructor code has to be changed

public class JavaInstructor implements Teacher {SpringCourseBook springBook = new SpringCourseBook();public void teach() {

System.out.println(springBook.getData());}

}

public class SpringCourseBook { // package statements not shown *public String getData() {

return "Dependencies are not so cool";}

}

Assume that all the classes in the examples in this session are in the com.javatunes.teach package

– We'll be leaving out all the package statements in the Java code examples for brevity

Session 1: Introduction to Spring

Evaluation Copy

Page 68: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 5820120607

Fast Track to Spring 3 and Hibernate

Dependency Inversion Principal

High level or low level modules should should depend upon abstractions and not upon each other– Use abstractions, e.g. interfaces, that all modules depend on– High level modules written in terms of abstractions (the

interfaces), and not directly in terms of low level modules– Dependencies still exist, but details not in implementation

classes

Using this design strategy has a number of advantages:

– Facilitates less coupled components• With a high degree of separation of responsibilities

– Produces greater flexibility• Implementations can be swapped without affecting other modules

– Facilitates reuse of components• They're less coupled to other parts of an application

Dependency Inversion is not a new idea– The idea of "Programming to Interfaces" has been around

since long before Java– It has been used in non-OO languages also, for example the

stdio module in the C programming language abstracted away the details of the actual devices doing the output

Many people don't use this design in building applications– Even though we know of good design principals, there is no

way to make sure people use themWe'll soon look at Spring's Dependency Injection which makes this design strategy even easier to useWe talk of modules here, which in Java are basically reflected as dependencies between different classes

Session 1: Introduction to Spring

Evaluation Copy

Page 69: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 5920120607

Fast Track to Spring 3 and Hibernate

Example of Dependency Inversion

Both JavaInstructor and SpringCourseBook depend on InfoSource – neither depend on the other

public class JavaInstructor implements Teacher {private InfoSource info;public void setInfo (InfoSource infoIn) {

info=infoIn;}public void teach() {

System.out.println(info.getData());}

}

public class SpringCourseBook implements InfoSource {public String getData() {

return "Dependencies are not so cool";}

}

public interface InfoSource {public String getData();

}

In the code example, we can see that JavaInstructor knows nothing about SpringCourseBook

– Instead, it depends on the InfoSource interface (the abstraction)

– When JavaInstructor is created, it is initialized with an instance of some InfoSource implementation

– However, it doesn't know any details of this implementation, and doesn't even know its exact type

SpringCourseBook likewise depends on the abstraction (it implements the InfoSource interface)

– The abstraction (the interface) is the common language that lets the different part of the system work together with depending directly on each other

Session 1: Introduction to Spring

Evaluation Copy

Page 70: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 6020120607

Fast Track to Spring 3 and Hibernate

Example of Dependency Inversion

In the example code below, JavaInstructor is initialized with a specific implementation of InfoSource (an instance of SpringCourseBook)– But JavaInstructor only sees this as the InfoSource type– It would make no difference to JavaInstructor if we initialized

it with some other type that implemented InfoSource – for example an EJBCourseBook

– We've decoupled the modules, and made them more flexible and easier to use, reuse, and maintain

public class TeachMeSpring {

public static void main(String[] args) {SpringCourseBook springBook = new SpringCourseBook();JavaInstructor myInstructor = new JavaInstructor();myInstructor.setInfo(springBook);myInstructor.teach();

}}

In the example above, we are still creating SpringCourseBookin a fairly straightforward way

– This exposes the actual implementation class of the lower level module (SpringCourseBook) in our TeachMeSpring code

– There are other, more sophisticated, ways to create these lower level modules

– For example, we could use factories of some sort to more completely abstract which InfoSource is being used

Whenever you have modules depending on one another, something has to know about the implementation details

– Even if it's abstracted through multiple layers, there is still a bottom layer somewhere which creates the instance of the actual implementation

– The goal is to do this in a way that makes your code easier to write, reuse, and maintain

We'll see how Spring deals with this soon

Session 1: Introduction to Spring

Evaluation Copy

Page 71: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 6120120607

Fast Track to Spring 3 and Hibernate

Dependency Injection (DI) in Spring

Using Dependency Injection, Spring allows you to abstract dependencies between modules even more– The Spring container can inject dependencies into a bean and

initialize them when it creates the bean– It can inject dependencies via constructors, properties in the

bean, or arguments to a factory method

Dependencies are defined in the Spring configuration file– The Spring container uses these dependency definitions to

initialize the bean– No need to explicitly initialize dependencies in your code

Your bean classes are still normal POJO classes– The Spring container only requires that you have the appropriate

methods needed to initialize the dependencies (e.g. setters)– There is nothing else special about the bean classes

Dependency injection is a fancy way of saying that the containerwill initialize all the dependencies in the bean when the bean is created

– The bean has to be a bean whose lifecycle is managed by the container

Session 1: Introduction to Spring

Evaluation Copy

Page 72: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 6220120607

Fast Track to Spring 3 and Hibernate

Dependency Injection Configuration

The Spring configuration below uses DI

– It declares two beans: springBook and springGuru– The <property name="info" ref="springBook"/> element tells

the container to initialize the info property of springGuru with the instance of SpringCourseBook defined above it

– It uses setter injection - calling JavaInstructor.setInfo()– You don't need to write any code for the injection to happen

<?xml version="1.0" encoding="UTF-8"?>

<beans … > <!-- Namespace declarations omitted -->

<bean id="springBook" class="com.javatunes.teach.SpringCourseBook"/>

<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"><property name="info" ref="springBook"/>

</bean>

</beans>

The container first creates an instance of SpringCourseBook, with the id springBookThe container next creates an instance of JavaInstructor using the no-arg constructor

– To accomplish the DI, the container calls the setInfo method, passing in the instance of SpringCourseBook that it had created

– The result is a fully initialized JavaInstructor instanceThe <property> element tells the container to use setter injection to initialize the dependency

– Setter injection uses the standard setter methods on your bean– It follows the standard property naming conventions, so if the property is named info, it

will call the setInfo method to initialize the dependency– There are other ways of initializing the dependency, such as constructor injection, that we'll

see laterThe bean reference can also be declared using a nested <ref> element as shown below<property name="info"><ref bean="springBook"/></property>

– Generally, the ref attribute shown in the slide is easier to use and understand– You can use the nested element if for some reason it is clearer to express it this way than as

an attribute (this is also provided for backwards compatibility with earlier Spring releases)

Session 1: Introduction to Spring

Evaluation Copy

Page 73: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 6320120607

Fast Track to Spring 3 and Hibernate

Dependency Injection Example

The example below shows how to use our beans with Spring– Notice that all our code is written completely in terms of the

abstract Teacher interface– Note also that our code, including the JavaInstructor class, is

totally decoupled from the concrete class SpringCourseBook– The JavaInstructor instance has its info property initialized

with a SpringCourseBook instance by the Spring container– The dependency is injected by the container transparently

// imports not shownpublic class TeachMeSpring {

public static void main(String[] args) {Resource res = new FileSystemResource("beans.xml");BeanFactory factory = new XmlBeanFactory(res);Teacher teacher = factory.getBean("springGuru", Teacher.class);teacher.teach();

}}

Note that your SpringCourseBook and JavaInstructor class definitions didn't need to change to use DI

– Of course, they had to support the design principle of Dependency Inversion, which we had already done

– Once this was done, we didn't need any changes or additional code to support DINote also that there is nothing in your TeachMeSpring code which shows that JavaInstructor depends on SpringCourseBook

– This is defined in your configuration, and handled for you by the containerNote that the no-arg constructor is present by default in JavaInstructor since we haven't defined any constructors at all

– If we defined constructors, and still wanted to use only setter injection, as for the configuration file in this example, we would have to include a no-arg constructor

– We'll take a look at constructor injection, which allows us to use constructor arguments, a little later

Session 1: Introduction to Spring

Evaluation Copy

Page 74: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 6420120607

Fast Track to Spring 3 and Hibernate

Advantages of Dependency Injection

DI reduces the coupling between modules in your code– Coupling is basically a measure of the dependencies

We've seen this reduction in two ways in our example:– JavaInstructor is not coupled to SpringCourseBook– TeachMeSpring is not coupled to JavaInstructor or SpringCourseBook

The dependencies are still there but not in the code– The dependency is moved to the spring configuration– They're injected into beans without your needing to write code– This is also commonly referred to as wiring beans together

This leads to more flexible code that is easier to maintain– At a cost – using Spring, and maintaining the spring configuration

Coupling is the measure of how much a module of code relies on other modules– Loosely coupled code is generally considered better code

Consider some of the following scenarios, and how DI makes them easier– Testing your code with testing framework such as JUnit can be much easier with DI – you

can configure the application to use mock objects wherever you want – without changing your code at all

– Testing different versions of classes can be done just by changing the configuration metadata

– In fact, any implementation class that implements the particular interfaces being used can be swapped into your program simply by changing the configuration information

There is debate about how worthwhile DI and frameworks like Spring are– However, the principles that it is based on that lead to loose coupling are widely accepted– Spring simply makes it easier to apply these principles– The effort required to adopt and use Spring is not trivial, but for larger projects the initial

cost of adopting Spring can be well worth it

Session 1: Introduction to Spring

Evaluation Copy

Page 75: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 6520120607

Fast Track to Spring 3 and Hibernate

Dependency Injection Reduces Coupling

The simplest case, JavaInstructor coupled to SpringCourseBook

JavaInstructor coupled to InfoSource only– TeachMeSpring coupled to JavaInstructor and SpringCourseBook

Using DI - TeachMeSpringonly coupled to Teacher– JavaInstructor only

coupled to InfoSource

JavaInstructor SpringCourseBook

InfoSource<<interface>>

creates

JavaInstructor

SpringCourseBookTeachMeSpringimplements

creates

InfoSource<<interface>>

TeachMeSpring

Teacher<<interface>> JavaInstructor

implements

looks up

BeanFactory

injects

In the DI example, the couplings are ONLY to interfaces– This is much better than being coupled to actual

implementation classes– It increases flexibility, testability, and ease of maintenance

Session 1: Introduction to Spring

Evaluation Copy

Page 76: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 6620120607

Fast Track to Spring 3 and Hibernate

Lab 1.3 – Dependency Injection

Lab 1.3: Dependency Injection

Evaluation Copy

Page 77: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 6720120607

Fast Track to Spring 3 and Hibernate

Lab 1.3 – Dependency Injection

Overview: In this lab, we will work with the DI capabilities of Spring– We will add a property (a dependency on another bean) to the JavaInstructor class, and initialize it using Spring DI

– The main program will not change at all– Again, the program is kept very simple so the concepts will be

clear

Objectives: – Become familiar with Spring DI, and use it in a program

Builds on previous labs: 1.2

Approximate Time: 20-30 minutes

Lab

Lab 1.3: Dependency Injection

Evaluation Copy

Page 78: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 6820120607

Fast Track to Spring 3 and Hibernate

Writing and Configuring a Bean in Spring

Tasks to PerformContinue to work in the Lab01.1 projectOpen up the SpringCourseBook.java file– Make sure that SpringCourseBook implements the InfoSource interface

Open up the JavaInstructor.java file– Add in a property called info, of type InfoSource– You'll need an instance field of type InfoSource, as well as a

setter method for this field– Modify the teach() method to print out the data from the info

properties getData() methodWe won't initialize the info property – that will be done with DI

Lab

All the classes we're working with are in the com.javatunes.teach package

Lab 1.3: Dependency Injection

Evaluation Copy

Page 79: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 6920120607

Fast Track to Spring 3 and Hibernate

Using a Bean in a Program

Tasks to PerformOpen up the src/beans.xml file– Add in a new bean element for SpringCourseBook

• Give it an id of springBook– Modify the <bean> element for springGuru by initializing it's info property with a <property> element• Use the springBook bean to initialize the info property

Run the program as before– The output should now be whatever data the SpringCourseBook returns

– The main program doesn't change at all – the JavaInstructordependency on SpringCourseBook is completely hidden

– JavaInstructor is decoupled from SpringCourseBook

Lab

Lab 1.3: Dependency Injection

Evaluation Copy

Page 80: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 7020120607

Fast Track to Spring 3 and Hibernate

Additional Things to Try (Optional)

In beans.xml, try leaving out the initialization of the springGuru bean's info property– Run your program– What happens? Why?

Change your code back to your original solution before going on

STOP

Lab

Lab 1.3: Dependency Injection

Evaluation Copy

Page 81: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 7120120607

Fast Track to Spring 3 and Hibernate

Review Questions

What is Spring?

How does Spring help you to build enterprise applications?

What is Dependency Injection, and how does it work in Spring

Session 1: Introduction to Spring

Evaluation Copy

Page 82: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 7220120607

Fast Track to Spring 3 and Hibernate

Lesson Summary

Spring is a lightweight framework for building enterprise applications whose capabilities include:– Dependency Injection, Persistence support (DAO and ORM),

AOP capabilities, integration with Web technologies, and its ownMVC based Web package

Spring helps you build complex enterprise applications by providing a non-intrusive, light weight solution for managing the complex dependencies and interactions between Java objects in your program.– It supplies many of the important capabilities of Java EE in a less

complex and lighter weight manner

Session 1: Introduction to Spring

Evaluation Copy

Page 83: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 7320120607

Fast Track to Spring 3 and Hibernate

Lesson Summary

Spring reinforces the use of loose coupling between components by promoting the technique of coding to interfaces, rather than concrete implementation classes– This by itself is an important design technique,

It provides support for initialization of beans and bean dependencies through configuration metadata– Usually done using XML configuration files

Dependency Injection is used by the Spring container to inject bean dependencies based on configuration information– This allows the complete decoupling of your types from concrete

implementation types

Session 1: Introduction to Spring

Evaluation Copy

Page 84: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 25220120607

Fast Track to Spring 3 and Hibernate

Session 5: Introduction to Hibernate

Hibernate OverviewUsing Hibernate

Mapping a Simple ClassLogging

Session 5: Introduction to Hibernate

Evaluation Copy

Page 85: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 25320120607

Fast Track to Spring 3 and Hibernate

Lesson Objectives

Describe the issues of object-relational mapping

Describe the overall goals of Hibernate

Describe the Hibernate architecture

Create a simple Hibernate application

Map a simple class to a DB using Hibernate

Session 5: Introduction to Hibernate

Evaluation Copy

Page 86: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 25420120607

Fast Track to Spring 3 and Hibernate

Hibernate Overview

Hibernate OverviewUsing Hibernate

Mapping a Simple ClassLogging

Session 5: Introduction to Hibernate

Evaluation Copy

Page 87: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 25520120607

Fast Track to Spring 3 and Hibernate

The Issues with Persistence Layers

Data is a core element of many applications– Data is often stored in relational databases

A great deal of effort is expended writing persistence layers tostore and retrieve data from the database– These layers are complicated to write– Often the "homegrown" persistence layer is buggy and

incomplete– Changes to the database schema are often expensive to

propagate to the persistence layer

When using an OO language, like Java, the situation is made more complicated

Persistence Layers have many complex requirements including:– Support of different databases, and potentially non-relational

databases– Full encapsulation of the underlying persistence mechanism– Coordination between multiple persistent objects– Support for transactions, and encapsulation of the underlying

transaction mechanism– Lazy loading for associations– Support for multiple simultaneous database connections– Support for using SQL queries when needed

Session 5: Introduction to Hibernate

Evaluation Copy

Page 88: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 25620120607

Fast Track to Spring 3 and Hibernate

Object-Relational Mapping (ORM) Issues

When using an OO language with a relational database, you are working with different models of using data– OO: Interacting objects traversed via relationships– Relational: Tables that are joined via foreign key relationships

These are very different models– Translating from one to the other requires work– There are many issues to deal with

Example, Inheritance: A core feature of OO models– Not supported in relational model

Relational Associations: only foreign key relationships– Object model: 1-1, 1-N, N-N

OO programming is base on software engineering conceptsRelational databases are based on mathematical principles

– The two models are different– Going back and forth between the two takes some work, a

good understanding of the structure of each, and enough experience to make good choices in choosing how to do the mapping

Session 5: Introduction to Hibernate

Evaluation Copy

Page 89: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 25720120607

Fast Track to Spring 3 and Hibernate

Issues with JDBC Alone

You don't store/load objects to the database– Everything has to be done with SQL

For example, to persist an object of some class– You need to write SQL statements to do this

To load an object from the database– You get result rows from the database, which must be converted

into objects

Session 5: Introduction to Hibernate

Evaluation Copy

Page 90: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 25820120607

Fast Track to Spring 3 and Hibernate

Hibernate Overview

Open Source, ORM framework for Java

Overall goals– Relieve the developer from 95% of common data persistence

related programming tasks– Provide ORM capability for using a Java OO domain model to

manage a relational database– Provide a light-weight POJO based framework for Java

persistence, including inheritance and polymorphism– Provide a query language that helps remove or encapsulate

vendor specific SQL code– Help with translation of result-set tables to object graph

Hibernate is an object/relational mapping tool for Java environments. The term object/relational mapping (ORM) refers to the technique of mapping a data representation from an object model to a relational data model with a SQL-based schema. Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC. Hibernates goal is to relieve the developer from 95 percent of common data persistence related programming tasks. Hibernate may not be the best solution for data-centric applications that only use stored-procedures to implement the business logic in the database, it is most useful with object-oriented domain models and business logic in the Java-based middle-tier. However, Hibernate can certainly help you to remove or encapsulate vendor-specific SQL code and will help with the common task of result set translation from a tabular representation to a graph of objects. [Hibernate 3.2.2 Reference Documentation, Preface]

Session 5: Introduction to Hibernate

Evaluation Copy

Page 91: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 25920120607

Fast Track to Spring 3 and Hibernate

Hibernate Benefits

Simplicity and flexibility– POJO based !– ORM is completely metadata driven (annotations or XML)– No need to write JDBC code – Common defaults that allow metadata to be minimized– Persistence API is totally separate from entity classes– Can be used in Java SE environments (without app server)

Completeness– Supports full range of OO features – Inheritance, custom object types, collections, associations– Powerful query language

Performance– Minimizes number of database updates– Lazy load on collections, disabling retrieval of associated objects– Object caching

Session 5: Introduction to Hibernate

Evaluation Copy

Page 92: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 26020120607

Fast Track to Spring 3 and Hibernate

Hibernate Environments

Can be used in Java SE or Java EE programs– It is packaged as a set of jar files– Only minor configuration and programming differences between

using it in a Java SE and Java EE environment

The Java Persistence API (JPA) derived a lot of it's structure from Hibernate– JPA is a required part of Java EE 5, and uses annotations to

specify mapping metadata about persistent classes– Hibernate supports the standard JPA annotations, in addition to

defining additional ones of its own– Using the JPA annotations with Hibernate gives a smooth

migration path to standard Java Persistence

Session 5: Introduction to Hibernate

Evaluation Copy

Page 93: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 26120120607

Fast Track to Spring 3 and Hibernate

Hibernate Architecture

Very high-level view– Hibernate uses database and configuration data to provide

persistence services and objects to the application– Many ways to architect this – we'll show two common ways

Session 5: Introduction to Hibernate

Evaluation Copy

Page 94: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 26220120607

Fast Track to Spring 3 and Hibernate

More Detailed Architecture

In this scenario, the application manages some details itself– Application manages JDBC connections and transactions– Uses minimal subset of Hibernate API– This can be considered Hibernate "Lite"

Session 5: Introduction to Hibernate

Evaluation Copy

Page 95: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 26320120607

Fast Track to Spring 3 and Hibernate

More Detailed Architecture

In this scenario, the app is abstracted away from JDBC/JTA– Hibernate takes care of these details– The application only interacts with the Hibernate API

We'll shortly take a look at the different types that are used to write a Hibernate application that are picture in this diagram

Session 5: Introduction to Hibernate

Evaluation Copy

Page 96: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 26420120607

Fast Track to Spring 3 and Hibernate

Using Hibernate

Hibernate OverviewUsing Hibernate

Mapping a Simple ClassLogging

Session 5: Introduction to Hibernate

Evaluation Copy

Page 97: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 26520120607

Fast Track to Spring 3 and Hibernate

Acquiring Hibernate

Hibernate is an open source project– It can be freely downloaded from http:://www.hibernate.org– Can get binary or source distributions– Can also view and download documentation (included in binary)

Hibernate Tools, a plugin for Eclipse is available at http://tools.hibernate.org and includes:– Mapping editor to create/manage Hibernate mapping files– Console that allows you to configure DB connections, visualize

classes and their relations, and execute queries interactively– Reverse engineering tools that can generate domain model

classes and Hibernate mapping files– Wizards for creating various Hibernate artifacts– ant task allowing you to run Hibernate tasks as part of your build

Session 5: Introduction to Hibernate

Evaluation Copy

Page 98: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 26620120607

Fast Track to Spring 3 and Hibernate

Using Hibernate

The Hibernate binary is a set of jar files– The main Hibernate jar, (hibernate3.jar for Hibernate 3 releases),

is included in the root of the hibernate distribution– A set of supporting jar files, is included in the lib directory of the

distribution• Not all the supporting jar files are always needed to run hibernate• There is a readme.txt file that tells what each jar is for and when it's

needed

In the labs, we give you instructions for configuring the full set of jar files you'll need to run Hibernate

Session 5: Introduction to Hibernate

Evaluation Copy

Page 99: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 26720120607

Fast Track to Spring 3 and Hibernate

Configuring Hibernate

Hibernate needs to be configured to connect to the specific database you are using

It also needs to be configured for the type of database– Hibernate may do things differently for different databases

The configuration can be done in multiple ways– Via an XML configuration file (named hibernate.cfg.xml by

default)– Via a properties file (named hibernate.properties by default)

• The properties file was used in earlier versions of Hibernate• It is still supported, but most users are now using the XML file

– Programmatically via a Java API

– We'll look mainly at the hibernate.cfg.xml file

Most users prefer the hibernate.cfg.xml XML file for configuration

– The properties file was used in earlier Hibernate versions, but has mostly been superseded by the XML configuration

– The programmatic configuration is useful if an application needs to dynamically configure its connection

Session 5: Introduction to Hibernate

Evaluation Copy

Page 100: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 26820120607

Fast Track to Spring 3 and Hibernate

Sample hibernate.cfg.xml

The configuration file has the structure shown below– A <session-factory> element contains the configuration for

the connection to the database– The file needs to be on the classpath

<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<!– Configuration for a SessionFactory instance --><session-factory></session-factory>

</hibernate-configuration>

Session 5: Introduction to Hibernate

Evaluation Copy

Page 101: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 26920120607

Fast Track to Spring 3 and Hibernate

hibernate.cfg.xml Elements

<hibernate-configuration> - The root element– Can contain a single <session-factory> element and an

optional <security> element<session-factory> - Information for creating a SessionFactory (representing a single DB)– <property> sub-elements used for much of the configuration

• Database information (connection info, database type …)• Specification of transaction behavior• Many properties – look at the docs. We show some common ones

– <mapping> elements specify entity class mapping files– <class-cache> and <collection-cache> contain cache

properties– <event> elements let you specify Hibernate events<security> contains security configuration information

Session 5: Introduction to Hibernate

Evaluation Copy

Page 102: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 27020120607

Fast Track to Spring 3 and Hibernate

SessionFactory Configuration

Needs to have the usual database information– Database JDBC URL– Database driver– User name, password– You may also specify a datasource name if you are using one

You can also specify a database dialect– This is the fully qualified classname of a class that customizes

Hibernate's behavior for a specific database

Other properties– Many other things that can be specified in the configuration– For example, caching related properties

Session 5: Introduction to Hibernate

Evaluation Copy

Page 103: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 27120120607

Fast Track to Spring 3 and Hibernate

SessionFactory Configuration Properties

There are many properties available– We show some of the important ones here – see the docs !– There are many properties to tune the connection, caching, transaction

JDBC Connection Properties– hibernate.connection.driver_class: jdbc driver class– hibernate.connection.url: jdbc URL– hibernate.connection.username: database user– hibernate.connection.password: database user password– hibernate.connection.pool_size: max pooled connections

DataSource Connection Properties– hibernate.connection.datasource: datasource JNDI name– hibernate.jndi.url, hibernate.jndi.class: JNDI Properties

Optional Configuration Properties– hibernate.dialect: Classname of a Hibernate Dialect– hibernate.show_sql: Write all SQL statements to console– hibernate.cache.provider_class: Classname of custom cache provider

There are way to many properties to cover in this course manual– See the Hibernate Reference Documentation Chapter 3

For example there are properties forJDBC Tuning

– hibernate.jdbc.fetch_size, hibernate.jdbc.batch_size, hibernate.jdbc.use_scrollable_resultset, hibernate.connection.provider_class, hibernate.connection.isolation, hibernate.connection.autocommit,hibernate.connection.<propertyName>, hibernate.jndi.<propertyName>

Hibernate Cache Properties– hibernate.cache.provider_class, hibernate.cache.use_query_cache,

hibernate.cache.use_second_level_cache, and moreHibernate Transaction Properties

– hibernate.transaction.factory_class, jta.UserTransaction, hibernate.transaction.manager_lookup_class, hibernate.transaction.flush_before_completion, hibernate.transaction.auto_close_session

hibernate.hbm2ddl.auto : Automatically validate or export schema DDL to the database when the SessionFactory is created. (validate | update | create | create-drop)

Session 5: Introduction to Hibernate

Evaluation Copy

Page 104: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 27220120607

Fast Track to Spring 3 and Hibernate

Example Properties for PostgresSQL

The example below shows properties that would be suitable if you were using the open-source PostgresSQL database

<!-- Other detail omitted --><session-factory><!-- Database Connection Settings --><property name="hibernate.connection.username">guest</property><property name="hibernate.connection.password">password</property><property name="hibernate.connection.url">

jdbc:postgres://localhost/db</property><property name="hibernate.connection.driver_class">

org.postgresql.Driver</property>

<!-- SQL Dialect --><property name="hibernate.dialect">

org.hibernate.dialect.PostgreSQLDialect</property>

<!-- Connection Pool Settings (uses built-in connection pool) --><property name="hibernate.connection.pool_size">1</property>

</session-factory>

The first four property elements contain the necessary configuration for the JDBC connection– The dialect property element specifies the particular SQL variant Hibernate generates. – If you're working in a J2EE environment, there are properties that allow you to specify a

datasource JNDI name (hibernate.connection.datasource)

Hibernate is the layer in your application which connects to this database, so it needs connection information

– The connections are made through a JDBC connection pool, which we also have to configure

– The Hibernate distribution contains several open source JDBC connection pooling tools, but this example uses the Hibernate built-in connection pool.

– Note that you have to copy the required library into your classpath and use different connection pooling settings if you want to use a production-quality third party JDBC pooling software

– [Hibernate 3.2.2 Reference Documentation, Section 1.2.3]

Session 5: Introduction to Hibernate

Evaluation Copy

Page 105: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 27320120607

Fast Track to Spring 3 and Hibernate

The Configuration Class

A Configuration instance is used to specify the configuration files that are read to configure Hibernate

– You usually create one instance of Configuration, and one instance of SessionFactory per application, usually via the following Configuration methods:

– A constructor configuring Hibernate via hibernate.properties– configure() configuring Hibernate via hibernate.cfg.xml

• There are also versions of configure that allow you to specify the configuration file name and location

– buildSessionFactory() creating a SessionFactory

– You can also configure Hibernate programmatically with a Configuration instance

– See the javadoc!

The Configuration instance is intended as a startup-time object, to be discarded once a SessionFactory is created.

– You can think of the Configuration instance as the in-memory Java representation of the configuration information

When you create a Configuration instance with its no-arg constructor, it will by default look for a hibernate.properties file in the root of the classpath

– If it finds hibernate.properties, it will load all the hibernate.* properties in this file, and add it to the instance

– If you call configure() on this instance (not required), hibernate searches for a file named hibernate.cfg.xml in the root of the classpath, and an exception is thrown if the file isn't found

– If it finds hibernate.cfg.xml, it reads the properties in the file, and adds them to the instance – overriding any already existing properties in the instance

We don't cover programmatic configuration, but the Configuration interface has methods that allow you to do the same things you can do with a configuration file

Session 5: Introduction to Hibernate

Evaluation Copy

Page 106: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 27420120607

Fast Track to Spring 3 and Hibernate

The SessionFactory Interface

A SessionFactory creates sessions– Its behavior is controlled by configuration properties– Usually an application has a single SessionFactory– A SessionFactory is immutable– It is an expensive-to-create, threadsafe object intended to be

shared by all application threads– It is created once, usually on application startup, from a Configuration instance.

It is a global factory responsible for a particular database– Configured by the hibernate.cfg.xml configuration file– This configuration defines the set of entities that can be

managed by a given Session instance– It defines the types that can be managed– It defines the database they are persisted to

Startup of a Hibernate application often includes building a global SessionFactory object and storing it somewhere for easy access in application code

– A SessionFactory can open up new Session's – A Session represents a single-threaded unit of work, the

SessionFactory is a thread-safe global object, instantiated once.

Hibernate supplies a sample HibernateUtil helper class which takes care of startup and makes accessing a SessionFactory convenient

– We'll look at this later

Session 5: Introduction to Hibernate

Evaluation Copy

Page 107: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 27520120607

Fast Track to Spring 3 and Hibernate

SessionFactory API

Here are some common methods of SessionFactory

– void close(): Destroy this SessionFactory and release all its resources (caches, connection pools, etc).

– Session openSession() - Create a database connection and open a Session on it

– public Session openSession(Connection connection): Open a Session on the given connection• For applications that manage JDBC connections themselves

– Session getCurrentSession() – Get the current session• We'll look later at the definition of what "current session" means

– Many more methods – see the documentation

It is the responsibility of the application to ensure that there are no open sessions before calling close() on the SessionFactoryThe API includes methods to:

– Evict objects and collections from the second level cache (covered later)

– Get metadata about entities managed by the factory

Session 5: Introduction to Hibernate

Evaluation Copy

Page 108: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 27620120607

Fast Track to Spring 3 and Hibernate

The Session Interface

Session is the main runtime interface used with Hibernate– Abstracts the notion of a persistence service– Inexpensive, non-threadsafe object that should be used once, for

a single request, or single unit of work, and then discarded– Won't obtain a JDBC Connection (or a Datasource) unless it is

needed, hence consumes no resources until used– Generally, you keep the session around for the duration of a

logical transactionSession has a number of capabilities– Saving: persisting objects to persistent storage– Deleting: removing objects from persistent storage– Updating: updating the persistent data of an entity– Loading: Retrieving an instance from persistent storage– We'll look at this interface in more detail later

The lifecycle of a Session is bounded by the beginning and end of a logical transaction

– Long transactions might span several database transactions.

The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes

Session 5: Introduction to Hibernate

Evaluation Copy

Page 109: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 27720120607

Fast Track to Spring 3 and Hibernate

Sessions and Transactions

By default, work done with a session is not persisted to the database until the associated transaction commits– Objects that are saved or updated are written to a transaction

cache for that session– When the transaction commits, the objects are written to the DB

You can work with transactions through the Hibernate API– We'll cover this in more detail later– You start a transaction and obtain an

org.hibernate.Transaction object from a session

Transaction tx = s.beginTransaction();

– You can commit or rollback via the transaction object

tx.commit(); // Commit the transaction

Session 5: Introduction to Hibernate

Evaluation Copy

Page 110: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 27820120607

Fast Track to Spring 3 and Hibernate

A Basic Hibernate Program Example

We start simply, and we'll cover more of the details later– The example just reads the configuration and connects to the DB

import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;

public class TestHibernate {public static void main(String[] args) {

SessionFactory sf;Session s;

try {sf = new Configuration().configure().buildSessionFactory();s = sf.openSession();s.beginTransaction();System.out.println("Session connect status: " + s.isConnected());s.getTransaction().commit();s.close();sf.close();

} catch (HibernateException e) { e.printStackTrace(); }}

}

This is the most common way of configuring and starting Hibernate in a Java SE Environment– The configuration will be looked for in the default hibernate.properties, and

hibernate.cfg.xml files (which must be in the classpath)

Note that Hibernate 3.x package names start with org.hibernate– Previous releases of Hibernate used the package prefix net.sf

Note the handling of the HibernateException– Many Hibernate methods throw this exception– It represents any exception that occurs inside the persistence layer or JDBC driver– SQLExceptions are always wrapped by instances of JDBCException– There are many, more specific, subclasses of HibernateException

Session 5: Introduction to Hibernate

Evaluation Copy

Page 111: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 27920120607

Fast Track to Spring 3 and Hibernate

Lab 5.1 – Setting up Hibernate

Lab 5.1: Setting up Hibernate

Evaluation Copy

Page 112: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 28020120607

Fast Track to Spring 3 and Hibernate

A Hibernate Application

Overview: In this lab, you will create a simple Hibernate application– We'll use the same Derby database as in the Spring JDBC labs

Objectives:– Configure hibernate and write a simple hibernate application

Builds on previous labs: NoneApproximate Time: 30-40 minutes

Note: We will be using the Hibernate implementation and supporting jars that come with Spring– This is the simplest way to integrate them together for the labs– We include the Spring library in this lab project's setup, but we

won't be integrating Hibernate/Spring until a later lab– The first few labs will use straight Hibernate for illustration

Lab

Lab 5.1: Setting up Hibernate

Evaluation Copy

Page 113: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 28120120607

Fast Track to Spring 3 and Hibernate

Create Hibernate User Library

Tasks to PerformGo to Window | Preferences | Java | Build Path | User Libraries– Click New…, call the library Hibernate, and press OK– Add the following jars to the Hibernate library (see notes)– From <spring>\dist, add *-aop-*.jar, *-aspects-*.jar, and *-orm-*.jar to

the Spring library (transaction jar also needed, but was added earlier)– From <spring-dep>, add the dependency jars for com.mchange.cp30,

javax.transaction, net.sourceforge.cglib (latest version only), net.sourceforge.ehcache, org.aopalliance, org.aspectj (all subdirs), org.dom4j, org.hibernate (all subdirs), org.jaxen, org.jboss.javassist, org.slf4j (only the latest API jar, not the jcl jar),

– From org.antlr, add the com.springsource.antlr version 2.7.6 jar– From org.apache.commons add the *.commons.collections subdir

(latest version only)– From org.objectweb.asm add from the *.asm (version 2.2.3) and

*.asm.attrs subdirs– From workspace\common\lib, add the slf4j-log4j12-* jar (see notes)

Lab

The jars listed in the slide (and there are a lot of them) are either needed by the Hibernate framework, or the Spring support for Hibernate - you'll need them to run the Hibernate labs

– A tool like maven can be helpful in managing the dependencies for production projects<spring> stands for the directory that Spring is installed in

– For example, C:\spring-framework-3.0.2.RELEASEAs when setting up the Spring User Library, you'll need to add in all the jars listed

– Each time you want to add jars, you'll need to select the Spring library in the User Libraries dialog, click the Add External JARs… button, browse to the appropriate directory, select the jars needed and click OK

Spring 3.0 contains Hibernate version 3.3– If you want, you can use a newer version of Hibernate, however it is not trivial to update

the Hibernate version, and we won't do it for the labsHibernate uses the slf4j logging framework to do logging

– It is a thin layer that then uses a bridge jar to bridge to a full logging framework– We'll use log4j as the logging framework - and so we need to add in the bridge jar (e.g.

slf4j-log4j12-1.5.6.jar), which is included in the setup, to do our actual logging

Lab 5.1: Setting up Hibernate

Evaluation Copy

Page 114: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 28220120607

Fast Track to Spring 3 and Hibernate

Create a Project for our Application

Tasks to PerformClose any open welcome screensCreate a Java Project *– Call the project Lab05.1– Eclipse will then automatically set

the project directory to Lab05.1– We supply an existing Lab05.1

directory, and Eclipse will configure the project based on the source in that directory

– Click Next– This will bring you to a dialog where

you can set the Java Settings for the project

Lab

To create a new Java Project, use the menuitem– File| New | Project | Java | 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 to use a new Lab directory

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

Lab 5.1: Setting up Hibernate

Evaluation Copy

Page 115: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 28320120607

Fast Track to Spring 3 and Hibernate

Add the Hibernate/Spring Libraries

Tasks to PerformIn 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 Hibernate and Spring, 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 libraries 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 5.1: Setting up Hibernate

Evaluation Copy

Page 116: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 28420120607

Fast Track to Spring 3 and Hibernate

Finish hibernate.cfg.xml

Tasks to PerformIn your Lab05.1 project, open src/hibernate.cfg.xml– It contains a skeleton configuration file– Fill in any required properties, with the info below (look for the TODO)– Look at the examples in the course manual

– User: guest– Password: password– DB URL: jdbc:derby://localhost:1527/JavaTunesDB

– This property is supplied for you in the config file– DB Driver: org.apache.derby.jdbc.ClientDriver– Dialect: org.hibernate.dialect.DerbyDialect– Connection Pool Size: 1

Lab

We include a few additional properties in the supplied configuration file

– One property echoes all of the executed SQL to stdout<property name="show_sql">true</property>

Lab 5.1: Setting up Hibernate

Evaluation Copy

Page 117: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 28520120607

Fast Track to Spring 3 and Hibernate

Create a TestClass

Tasks to PerformTest the configuration using a test class– Open the class TestHibernate which is in the default package– In the main method, create a Configuration, a SessionFactory,

and then a Session– Print out a message that tells whether or not the Session is connected– Look at the examples in the course manual– Don't forget to import the classes you need (see next slide)

The test class should compile cleanly– We are using Hibernate classes, but we have the Hibernate jars on

the Java build path for the Hibernate project in Eclipse

Lab

We use the jars that come with the Hibernate distribution for the labs– The hibernate3.jar file is the main jar file, and is in the hibernate home directory– There are dependency jars in the lib directory under hibernate home

• These are libraries that Hibernate uses

Lab 5.1: Setting up Hibernate

Evaluation Copy

Page 118: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 28620120607

Fast Track to Spring 3 and Hibernate

Eclipse Hint - Importing

One of the nicest features of Eclipse is its auto-import feature– To try it out, in your TestHibernate.java file, remove the import for

Session if you've already put it in (if you haven't imported it, then just continue below)

– in your TestHibernate.main() method, type Session, then type Ctrl-Space

– Select the org.hibernate entry and hit return– An import org.hibernate.Session statement will very

conveniently be added at the top of your source file

Lab

Eclipse can help you with importing classes that you need– When you use a class, and it's not properly imported, Eclipse

notices, and marks if for you– If you move your cursor into or at the end of the class name,

and type Control-space, it will bring up a window with possible classes to import

– You can select the class you want, and Eclipse will automatically add in the import for you

Lab 5.1: Setting up Hibernate

Evaluation Copy

Page 119: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 28720120607

Fast Track to Spring 3 and Hibernate

Running Your Application

Tasks to PerformAfter a clean build (one that is error-free, but not necessarily warning-free), test the application– In the Package Explorer

pane, right click on the TestHibernate.java file

– Select:Run As -> Java Application

– This will automatically find the main method in TestHibernate and run it for you

Lab

Lab 5.1: Setting up Hibernate

Evaluation Copy

Page 120: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 28820120607

Fast Track to Spring 3 and Hibernate

Testing your Application

If everything is set up correctly, the program should runYou will see the results in the console view (bottom panel by default)– Ignore any output related to logging - we will cover this later

Lab

Lab 5.1: Setting up Hibernate

Evaluation Copy

Page 121: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 28920120607

Fast Track to Spring 3 and Hibernate

Debugging Problems

Tasks to PerformIf you fail to connect to the database do the following– Look at the error messages– Check to see that the database server is running– Make sure that the database URL is correct– Did you create the database?– Try using the dbSQL command to connect to the database– Ask for help from the instructor if you still can't connect

Lab

Note, that when you want to run the application again, you can click the run button arrow on the task bar– This brings up a list of all the

run configurations you've recently used STOP

Lab 5.1: Setting up Hibernate

Evaluation Copy

Page 122: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 29020120607

Fast Track to Spring 3 and Hibernate

Mapping a Simple Class

Hibernate OverviewUsing Hibernate

Mapping a Simple ClassLogging

Session 5: Introduction to Hibernate

Evaluation Copy

Page 123: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 29120120607

Fast Track to Spring 3 and Hibernate

Persistent Entity Classes

A persistent entity class is a lightweight persistent domain object– They are fine-grained objects representing state stored in a DB– Entity classes are one of the primary programming artifacts of

Hibernate

Entity classes Must be persistable – i.e. have a database representation– Have a persistent identity – basically the primary key in the DB– Are normally created/updated/deleted within a transaction

Metadata describes the mapping to the data store– Can be done with XML or annotations (new in Hibernate 3)– The metadata required is minimized through the use of intelligent

defaults

Hibernate supports annotations that are compatible with the JavaPersistence API

– It is likely that these annotations will eventually become the preferred way of specifying metatdata for persistent classes

Hibernate originally used the name "persistent class" to describe a class that was mapped to the database

– The Java Persistence API introduced the term "entity class"– They are usually used interchangeably in Hibernate literature

today– We will use both terms to mean the same thing

Session 5: Introduction to Hibernate

Evaluation Copy

Page 124: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 29220120607

Fast Track to Spring 3 and Hibernate

Persistent Classes

Persistent classes work best if they follow a few simple rules– Implement a no argument constructor for Hibernate to

instantiate instances through reflection (required)– Declare getter/setter methods for all persistent fields (optional)– Provide an identifier property (usually called id) (optional)

• Maps to primary key column of database• Primitive type, or primitive wrapper, String, Date, composite key• Theoretically optional, but required for use of the full feature set of

Hibernate– Implement equals() and hashcode() (optional)

• Necessary if you mix instances created in different sessions– If instances will be passed as a detached object through a

remote interface, the class must implement Serializable

Session 5: Introduction to Hibernate

Evaluation Copy

Page 125: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 29320120607

Fast Track to Spring 3 and Hibernate

An Example Persistent Class

package com.javatunes;

import java.util.Date;

public class Event {

private Long id; // Property for database idprivate String title; private Date date;

Event() {}

public Event(Long id) { setId(id); }

public Long getId() { return id; }private void setId(Long id) { this.id = id; }

public Date getDate() { return date; }public void setDate(Date date) { this.date = date; }

public String getTitle() { return title; }public void setTitle(String title) { this.title = title; }

}

Session 5: Introduction to Hibernate

Evaluation Copy

Page 126: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 29420120607

Fast Track to Spring 3 and Hibernate

The Event Class

The event class has three properties– id (Long), date (java.sql.Date), title (String)– The id property holds a unique identifier for each event– The class has JavaBean style get/set methods for all the

properties– The class also has no-argument constructor

By default, no properties are persistent– That is, they are not stored in the database– A mapping file is used to specify persistent fields

Note that the setter for id is private – Programs will not be allowed to change this value

Session 5: Introduction to Hibernate

Evaluation Copy

Page 127: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 29520120607

Fast Track to Spring 3 and Hibernate

The id Property

The id property will hold the primary key of the entity– A class must have a primary key, and it is highly recommended

that you define a property to hold it– A non-composite primary key must correspond to a single field in

an entity (e.g. the id field in the Event class)

A simple primary key must be one of the following:– Java primitive or wrapper class (integral types most common)– java.lang.String, java.util.Date, java.sql.Date

Generated primary keys are supported– Only integral types will be portable

Composite primary keys are also possible– These use a primary key class

The identifier property is strictly optional. You can leave them off and let Hibernate keep track of object identifiers internally. We do not recommend this, however. In fact, some functionality is available only to classes which declare an identifier property:

– Transitive reattachment for detached objects (cascade update or cascade merge) – Session.saveOrUpdate() – Session.merge()

We recommend you declare consistently-named identifier properties on persistent classes. We further recommend that you use a nullable (ie. non-primitive) type. [Hibernate 3.2.2 Reference Documentation, Section 4.1.2] A composite primary key must correspond to either a single persistent field or property or to a set of such fields or properties

– A primary key class must be defined to represent a composite primary key– Composite primary keys typically arise when mapping from legacy databases when the

database key is comprised of several columns– @EmbeddedId and @IdClass are used to denote composite primary keys

Session 5: Introduction to Hibernate

Evaluation Copy

Page 128: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 29620120607

Fast Track to Spring 3 and Hibernate

The Hibernate Mapping File

Specifies the mapping of your entity classes to the DB– Here is the top-level structure of the mapping file– This declares this to be a mapping for the Event class, with a

mapping to the EVENTS table– The name of the mapping file is generally named after the class

(e.g. Event.hbm.xml for the Event class)

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="com.javatunes.Event" table="EVENTS"><!-- Property Mappings … -->

</class>

</hibernate-mapping>

Note that the Hibernate DTD is very sophisticated. You can use it for auto-completion of XML mapping elements and attributes in your editor or IDE. You also should open up the DTD file in yourtext editor - it's the easiest way to get an overview of all elements and attributes and to see the defaults, as well as some comments. Note that Hibernate will not load the DTD file from the web, butfirst look it up from the classpath of the application. The DTD file is included in hibernate3.jar as well as in the src/ directory of the Hibernate distribution.

[Hibernate Reference Documentation]

Session 5: Introduction to Hibernate

Evaluation Copy

Page 129: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 29720120607

Fast Track to Spring 3 and Hibernate

The <hibernate-mapping> Element

Root element of the mapping file– Usually contains a single <class> element mapping one class– Legal to have multiple <class> elements, but not recommended

Has optional attributes that affect all mappings in the file– schema: The name of a database schema. – catalog: The name of a database catalog. – default-cascade (default=none): Default cascade style. – default-access (default=property): The strategy Hibernate

should use for accessing all properties– default-lazy (default=true): The default value for unspecified lazy

attributes of class and collection mappings. – auto-import (default=true): Can we use unqualified class names

(of classes in this mapping) in the query language. – package: Package prefix for unqualified class names in mapping

Session 5: Introduction to Hibernate

Evaluation Copy

Page 130: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 29820120607

Fast Track to Spring 3 and Hibernate

The <class> Element

Declares a persistent class– Contains sub-elements that declare the persistent properties of

the class

Has a large number of optional attributes affecting the mapping of the persistent class– We show some of the more common ones here – see the docs– name: Fully qualified Java class name of the persistent class– table (default=unqualified class name): name of its DB table– mutable (default=true): Specifies if instances are (not) mutable – entity-name (default= class name): Name of this entity as used

in queries, other mappings

If you use the package attribute in the <hibernate-mapping> element, and the class is in the same package, then you don't need to fully qualify it in the name attribute

<hibernate-mapping package="com.javatunes">

<class name="Event" table="EVENTS">

<!-- Property Mappings … -->

</class>

</hibernate-mapping>

Hibernate3 allows a class to be mapped multiple times (to different tables, potentially), and allows entity mappings that are represented by Maps or XML at the Java level. In these cases, you should provide an explicit arbitrary name for the entity with the entity-name attribute

Session 5: Introduction to Hibernate

Evaluation Copy

Page 131: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 29920120607

Fast Track to Spring 3 and Hibernate

The EVENTS Table

Let's assume that the EVENTS table is declared as below

Assume you are using a generated primary key– A very common situation– The SQL shown is for the open source Derby database using an

Identity column

Let's look at how to map our Event class

CREATE TABLE EVENTS(

EVENT_ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),

EVENT_DATE DATE,TITLE VARCHAR(80),CONSTRAINT PK_EVENTS PRIMARY KEY(EVENT_ID)

);

Session 5: Introduction to Hibernate

Evaluation Copy

Page 132: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 30020120607

Fast Track to Spring 3 and Hibernate

Mapping the id Property with <id>

The <id> element declares the primary key in the database– The name attribute specifies the property it is mapped to (id)– The column attribute maps this to the EVENTS table's primary

key column (EVENT_ID)– We also configure Hibernate to automatically generate the

primary key value for us

<hibernate-mapping>

<class name="com.javatunes.Event" table="EVENTS"><id name="id" column="EVENT_ID">

<generator class="identity"/></id>

</class>

</hibernate-mapping>

Mapped classes must declare the primary key column of the database table. Most classes will also have a JavaBeans-style property holding the unique identifier of an instance. The <id> element defines the mapping from that property to the primary key column. [Hibernate 3.2.2 Reference Documentation, Section 5.1.4]

The id property can have any name– It is customary to call it id

Session 5: Introduction to Hibernate

Evaluation Copy

Page 133: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 30120120607

Fast Track to Spring 3 and Hibernate

More About Primary Keys

Hibernate requires that every entity have a primary key– Just as every row in a database needs a primary key

In modern database schemas, primary keys are usually surrogate, artificially generated keys– Though legacy databases might have so called "natural" keys

which represent some combination of business data– Natural keys are sub-optimal for many reasons

Hibernate primary key requirements are basically the same as for relational tables in general– Primary key must be non-null, unique, and immutable– Hibernate also needs to know how the key is created, since the

primary key can be auto-generated in different waysHibernate has extensive support for dealing with primary keys– For surrogate, generated keys, and for natural keys

Session 5: Introduction to Hibernate

Evaluation Copy

Page 134: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 30220120607

Fast Track to Spring 3 and Hibernate

Generating the id Value

The <generator> element specifies a generated key– It declares a class used to generate the id value– There are many options to deal with generating this primary key,

including letting the database or Hibernate generate it– The following generators create keys of type long, short or int

– increment: Identities unique only when no other process is inserting into the table (not for cluster)

– identity: Uses identity columns for databases supporting it– sequence: Uses a sequence for databases supporting it– hilo: Uses a hi/lo algorithm to efficiently generate identifiers

– assigned: lets application assign value before a save()• Often used for natural keys

– More are available – See the documentation

Session 5: Introduction to Hibernate

Evaluation Copy

Page 135: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 30320120607

Fast Track to Spring 3 and Hibernate

Mapping Properties with <property>

The <property> element declares persistent properties– By default, no properties are considered persistent– The name attribute specifies the property name in the class– The column attribute specifies the column name in the database

• Here we've mapped the date property to the EVENT_DATE column– The type attribute specifies the Hibernate type of the property– The title property will map to the TITLE column by default, and

the type will be determined by Hibernate<hibernate-mapping>

<class name="com.javatunes.Event" table="EVENTS"><id name="id" column="EVENT_ID">

<generator class="increment"/></id><property name="date" type="date" column="EVENT_DATE"/><property name="title"/>

</class>

</hibernate-mapping>

Session 5: Introduction to Hibernate

Evaluation Copy

Page 136: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 30420120607

Fast Track to Spring 3 and Hibernate

Hibernate Mapping Types

The type of the date property is specified as a Hibernate Mapping Type

– These are converters which can translate from Java to SQL data and vice versa

– If this attribute is not specified, Hibernate will try to determine the correct mapping

– In the case of a Java Date, Hibernate can't really tell if it should map to a SQL date, timestamp, or time column, so we specified itin the mapping

– The title property maps to the TITLE column, which is a VARCHAR, and the defaults work for this

The challenge is to map the Java type system to the SQL/databasetype system

– The bridge between both systems is provided by Hibernate: – For value types we use <property>, <component>, etc,

usually with a type attribute– The value of this attribute is the name of a Hibernate

mapping type– Hibernate provides many mappings (for standard JDK value

types) out of the box– You can write your own mapping types and implement your

custom conversion strategies as well, as you'll see later[Hibernate 3.2.2 Reference Documentation, Section5.2.1]

Session 5: Introduction to Hibernate

Evaluation Copy

Page 137: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 30520120607

Fast Track to Spring 3 and Hibernate

Common Hibernate Type Mappings

integer, long, short, float, double, character, byte, boolean, yes_no, true_false

– Type mappings from Java primitives or wrapper classes to appropriate (vendor-specific) SQL column types.

– boolean, yes_no and true_false are all alternative encodings for a Java boolean or java.lang.Boolean

string

– java.lang.String to VARCHAR (or Oracle VARCHAR2)date, time, timestamp

– java.util.Date and its subclasses to SQL types DATE, TIME and TIMESTAMP (or equivalent)

calendar, calendar_date

– Type mappings from java.util.Calendar to SQL types TIMESTAMPand DATE (or equivalent).

big_decimal

– java.math.BigDecimal to NUMERIC (or Oracle NUMBER).

Session 5: Introduction to Hibernate

Evaluation Copy

Page 138: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 30620120607

Fast Track to Spring 3 and Hibernate

Field Access or Property Access

By default, the persistence runtime will access the persistent fields using JavaBean style accessor methods (get/set/is)

– Hibernate considers this better style than accessing fields directly– This can be useful if you have business logic in the accessor

methods (e.g. validation logic)– You may switch to direct field access for particular properties, if

needed (see below)– In that case, the runtime will access the fields directly– In the example below, we specify that the Hibernate runtime

should access the title field directly rather than through the get/set methods

<property name="title" access="field"/>

Caution should be exercised in adding business logic to the accessor methods when property-based access is used. The order in which the persistence provider runtime calls these methods when loading or storing persistent state is not defined. Logic contained in such methods therefore cannot rely upon a specific invocation order. [JPA Specification, 2006, sec. 2.1.1]

Session 5: Introduction to Hibernate

Evaluation Copy

Page 139: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 30720120607

Fast Track to Spring 3 and Hibernate

The Mapping File

The file would normally be called Event.hbm.xml– It can be placed in the same directory as the Event.class file– This, of course, should be on the classpath

You specify that the mapping exists by including a reference to it in the hibernate.cfg.xml file, as shown below– It can also be specified programmatically via the Configuration

object

<!-- Other detail omitted --><session-factory><!-- Properties – detail omitted -->

<!-- Mapping Files --><mapping resource="com/javatunes/Event.hbm.xml"/></session-factory>

Session 5: Introduction to Hibernate

Evaluation Copy

Page 140: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 30820120607

Fast Track to Spring 3 and Hibernate

Hibernate Sessions

A session is required to actually interact with the database, to create, read, or write a mapped entity– Without a session, your types are just POJOs

The session also manages entity instances– When the session obtains an entity reference, the referenced

object becomes a persistent (or managed) entity

The Session interface defines the methods used for working with entities– It is used to create and remove persistent entity instances, to find

entities by their primary key, and to query over entities

The session is configured to work with a data store via the SessionFactory that produces it

Note that a session is not thread safe– It is meant to be used by a single thread at a time

Entities are also intended to be accessed by a single thread at a time while they are being managed

– Really they also shouldn't be accessed by multiple threads when they are detached (which we talk about later)

– However, if you want to manage the thread safety in the entity instance for when it's detached, it's possible to do so

– It's not desirable– Its better to make copies and merge the state back into a persistence context

Session 5: Introduction to Hibernate

Evaluation Copy

Page 141: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 30920120607

Fast Track to Spring 3 and Hibernate

The Session Interface

Some of the important Session methods are:– Object get(Class entityClass, Serializable id):

Retrieve entity with the given id, returning null if no matching row– Object load(Class entityClass, Serializable id):

Retrieve entity with given id, throwing exception if no match– public Serializable save(Object entity): Make a new

entity instance managed and persistent– void refresh(Object entity): Refresh the state of the

instance from the DB, overwriting any changes to the entity– void delete(Object entity): Remove the entity instance

from the DB

There are many more methods– We will use this interface extensively in the course– See the documentation !

Note that load() will throw an unrecoverable exception if there is no matching database row. If the class is mapped with a proxy, load() just returns an uninitialized proxy and does not actually hit the database until you invoke a method of the proxy. This behaviour is very useful if you wish to create an association to an object without actually loading it from the database. It also allows multiple instances to be loaded as a batch if batch-size is defined for the class mapping.

– If you are not certain that a matching row exists, you should use the get() method, which hits the database immediately and returns null if there is no matching row. [Hibernate 3.2.2 Reference Documentation, Section 10.3]

refresh() is useful in certain situations, such as when database triggers modify an object on insert or update, or when direct SQL has been used

Session 5: Introduction to Hibernate

Evaluation Copy

Page 142: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 31020120607

Fast Track to Spring 3 and Hibernate

Retrieving Persistent Objects

Here's how to use the Session.get() method to retrieve persistent objects– get() requires that you pass in the id of the entity you want– It returns the persistent instance of the given entity class with the

given identifier, or null if no persistent instance with the given id is found

– get() will go to the database immediately to retrieve an entity

// much code omitted ...

SessionFactory sf = new Configuration().configure().buildSessionFactory();Session s = sf.openSession();s.beginTransaction();Long id = new Long(1);Event e = (Event)s.get(Event.class,id);System.out.println("Retreived event: " + e.getTitle());s.getTransaction().commit();s.close();sf.close();

load() has different behavior from get() in the following ways– load() may not go to the database immediately– If the entity is one that can be lazily loaded (covered later)

Hibernate may return an unitialized proxy to the object (basically a wrapper around the id value)

– When the proxy is accessed for information besides the id, then Hibernate will go to the database

– Note that load() will throw an exception if the id is not found (as opposed to get() which returns null)

– Note also that this exception may not be thrown immediately, but only when Hibernate actually goes to the database

Session 5: Introduction to Hibernate

Evaluation Copy

Page 143: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 31120120607

Fast Track to Spring 3 and Hibernate

Lab 5.2 – Creating a Mapping File

Lab 5.2: Creating a Mapping File

Evaluation Copy

Page 144: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 31220120607

Fast Track to Spring 3 and Hibernate

Lab – A Hibernate Mapping File

Overview: In this lab you will create a Hibernate mapping file for a simple Java class – the MusicItem class– This is a simple class that has JavaBean type properties– It maps to the Item table in our database, which was created

when you ran dbCreate in the earlier lab– We will show you the class definition and database schema

Objectives:– Create and work with a simple Hibernate mapping file

Builds on previous labs: Lab 5.1

Approximate Time: 20-30 minutes

Lab

Lab 5.2: Creating a Mapping File

Evaluation Copy

Page 145: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 31320120607

Fast Track to Spring 3 and Hibernate

The MusicItem Class

com.javatunes.persist.MusicItem– A JavaBean-style value class that represents a CD, that has the

following public methods to access its attributes

public Long getId() // DB Primary Keypublic String getNum() // CD Numberpublic String getName()public String getArtist()public java.sql.Date getReleaseDate()public BigDecimal getListPrice()public BigDeicmal getPrice()

– It also has set methods for all its attributes– The setId() method is private, all the others are public

This class is already supplied for you in the setup

Lab

Lab 5.2: Creating a Mapping File

Evaluation Copy

Page 146: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 31420120607

Fast Track to Spring 3 and Hibernate

The Database Table for MusicItem

The database table for MusicItem is defined as shown below– This was already created when we created the database– Notice that the table name is Item– Notice that ID (in the ITEM_ID column) is an Identity column– Note the names and types of the other properties

CREATE TABLE Item(

ITEM_ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),

NUM VARCHAR(10) NOT NULL,Title VARCHAR(40),Artist VARCHAR(40),ReleaseDate DATE,ListPrice DECIMAL(5,2),Price DECIMAL(5,2),Version INTEGER,CONSTRAINT PK_Item PRIMARY KEY(ITEM_ID)

);

Lab

Lab 5.2: Creating a Mapping File

Evaluation Copy

Page 147: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 31520120607

Fast Track to Spring 3 and Hibernate

JavaTunes O-R Mapping

Mapping of the Item table to the MusicItem class– An Item table row becomes a MusicItem object

BIGINTITEM_ID

(PK)

VARCHARNum

VARCHARTitle

VARCHARArtist

DATEReleaseDate

DECIMALListPrice

DECIMALPrice

1 CD501 Diva Annie Lennox 1992-01-04 17.97 13.99

. . . . . . . . . . . . . . . . . .

21 CD521 Music Madonna 2002-02-27 14.99 11.97

MusicItem

Long id;String num;String title;String artist;Date releaseDate;BigDecimal listPrice;BigDecimal price;

MusicItem Classitem_id 21num CD521title Musicartist MadonnareleaseDate 2002-02-27listPrice 14.99price 11.97

Item Table

Lab

Notice how we map each Item table column to an MusicItemmember variable:

– column name (SQL) -> variable name (Java)– column type (SQL) -> variable type (Java)

Lab 5.2: Creating a Mapping File

Evaluation Copy

Page 148: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 31620120607

Fast Track to Spring 3 and Hibernate

Create a Mapping File

Tasks to PerformOpen the filesrc/com/javatunes/persist/MusicItem.hbm.xml– This contains a skeleton mapping file– Use the Source mode tab in the Eclipse XML Editor– Add the remaining property elements – one for each property in

the MusicItem class / Item table– The property names and columns are self-evident– We give any other needed information below

– id: Should use the identity generator– releaseDate: Should be of type date– listPrice and price: Should be of type big_decimal– All String properties should be mapped as type string

Lab

Lab 5.2: Creating a Mapping File

Evaluation Copy

Page 149: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 31720120607

Fast Track to Spring 3 and Hibernate

Add the Mapping to the Configuration

Tasks to PerformAdd the mapping file to the hibernate configuration file (hibernate.cfg.xml) with a mapping element of:<mapping resource="com/javatunes/persist/MusicItem.hbm.xml"/>

Run your TestHibernate program again– You should get no exceptions on the console– We don't need to add any code to TestHibernate yet– After we add the <mapping> element to hibernate.cfg.xml, the

Hibernate runtime will read the mapping file when TestHibernate runs

– If there are any errors in the mapping file, exceptions will be thrown in the console - so keep working until you have no errors

Lab

You should run the program in the same way that you did in the first lab

– Run the application from within Eclipse

Lab 5.2: Creating a Mapping File

Evaluation Copy

Page 150: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 31820120607

Fast Track to Spring 3 and Hibernate

Retrieve a Persistent Entity

Tasks to PerformOnce you're sure that your mapping file is correct, retrieve an instance of MusicItem using the session object you created in your test program– Use the session's get() method– Try it with an id of 1L *– Print out some information from the instance, to see that you

actually retrieved itRun the program and check your output

That's it – no mess, no fuss, no JDBC code– You'll soon see how easy it is to insert or query entities also

Lab

1L means a value of 1 as a long– If you just use 1, it is an integer, which will not compile, even

though it's the correct value

Lab 5.2: Creating a Mapping File

Evaluation Copy

Page 151: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 31920120607

Fast Track to Spring 3 and Hibernate

[Optional] Auto Completion in Eclipse

Tasks to PerformGo back to MusicItem.hbm.xml in the Eclipse Editor– Make sure you're in source mode for this file– Type Ctrl-Space in the file below <hibernate-mapping>– You'll see an auto-completion list of allowable elements that includes

explanations of what they are for

Group

Lab 5.2: Creating a Mapping File

Evaluation Copy

Page 152: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 32020120607

Fast Track to Spring 3 and Hibernate

[Optional] Design Mode for Config files

Tasks to PerformNotice that you now have a design and source mode represented by tabs on the bottom of the editor pane– Work now in the design mode by clicking the Design tab– Right click on the an element, and you'll see menus that allow you to

add in allowable elements– We show this below for the hibernate.cfg.xml file– This is available for mapping files also

Group

STOP

Lab 5.2: Creating a Mapping File

Evaluation Copy

Page 153: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 32120120607

Fast Track to Spring 3 and Hibernate

Logging

Hibernate OverviewUsing Hibernate

Mapping a Simple ClassLogging

Session 5: Introduction to Hibernate

Evaluation Copy

Page 154: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 32220120607

Fast Track to Spring 3 and Hibernate

hibernate.show_sql

Your console output for the labs will have shown you some debugging output– This is coming from a number of sources– The line that includes "select musicitem0_.ITEM_ID …" is output

that is produced because we set hibernate.show_sql to true in hibernate.cfg.xml

– You will likely also have debugging output from Hibernate (depending on your environment – see next slide)

– The example below shows output from log4j in red

Session 5: Introduction to Hibernate

Evaluation Copy

Page 155: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 32320120607

Fast Track to Spring 3 and Hibernate

Simple Logging Facade for Java - SLF4J

Hibernate 3.3+ uses SLF4J to do its loggingSLF4J can direct your logging output to several logging frameworks depending on your chosen binding– NOP, Simple, log4j version 1.2, JDK 1.4 logging, JCL or logback

To set up logging properly you will need slf4j-api.jar in your classpath together with the jar file for your preferred binding– slf4j-api.jar comes with the Hibernate distribution– You will need a jar for your binding, and the actual logging

implementation For the labs, we have chosen to use log4j, which uses the SLF4J binding jar (slf4j-log4j12.jar) as well as the log4j jar– Included in the Hibernate library you set up– When they're on the classpath, log4j is used as your logging

implementation by Hibernate

We will work with log4j, since it is a widely used, very powerful logging framework– To use log4j you will need to place a log4j.properties file in your classpath

If you wanted to use a different logging implementation, you'd need to get the jar for that binding from the slf4j website (http://www.slf4j.org), and include it in the classpath (as well as any other needed files for the logging implementation)Earlier releases of Hibernate (e.g. Hibernate 3.2) used Apache commons-logging

– The commons-logging service will direct output to either Apache Log4j (if you include log4j.jar in your classpath) or JDK1.4 logging (if running under JDK1.4 or above)

Hibernate 3.2, included the log4j jar file in the distribution (under <hibernate>\lib)– In the labs, you would include it when you create the Hibernate User Library - which would

have resulted in the Hibernate runtime using log4j as its logging implementation

Session 5: Introduction to Hibernate

Evaluation Copy

Page 156: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 32420120607

Fast Track to Spring 3 and Hibernate

Apache Log4J

Log4j is an open source framework that allows developers to control how log statements are output with arbitrary granularity– Hibernate is already set up to produce log4j output – i.e. it

includes logging statements in its implementation

It is possible to configure the logging output from Hibernate via the log4j configuration file– To do this, we'll need to include the log4j library (log4j-nnn.jar)

and configuration file (log4j.properties) in our labs– This will allow us to explicitly configure and then view the log4j

output from Hibernate

We don't go deeply into the details of Log4j here

The logging statements in the Hibernate distribution may or may not produce output depending on how you configure log4j

Session 5: Introduction to Hibernate

Evaluation Copy

Page 157: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 32520120607

Fast Track to Spring 3 and Hibernate

Hibernate log4j.properties file

The Hibernate distribution ships with a sample log4j.propertiesfile which includes entries for the major loggers that Hibernatewrites to in it's implementation– If you want to configure the debugging information that your

Hibernate programs output, you can start with this file– It is usually in the [hibernate]\doc\tutorial\src directory– We supply it for you in the lab setup

The Hibernate reference manual says the following:– "We strongly recommend that you familiarize yourself with

Hibernate's log messages. A lot of work has been put into making the Hibernate log as detailed as possible, without makingit unreadable. It is an essential troubleshooting device."

Session 5: Introduction to Hibernate

Evaluation Copy

Page 158: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 32620120607

Fast Track to Spring 3 and Hibernate

The log4j.properties file

This sample from the Hibernate distribution shows:– An appender, stdout, which directs output to the console, with a

logging level of warn– The root logger, which sets up defaults for all loggers– A hibernate logger, org.hibernate, with a logging level of info

• With output to the stdout appender inherited from the root logger

### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.rootLogger=warn, stdout

log4j.logger.org.hibernate=info## More detail omitted ...

Session 5: Introduction to Hibernate

Evaluation Copy

Page 159: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 32720120607

Fast Track to Spring 3 and Hibernate

Modifying log4j.properties for Hibernate

It's easy to change the debugging messages that Hibernate outputs– Output from log4j is controlled and organized by categories– For example, the line below states that all messages from the

category org.hibernate, of info level or above, should be outputlog4j.logger.org.hibernate=info

– If you want even more error messages, then you could change that level to be all messages of debug level (the lowest level) or above by changing that line to read

log4j.logger.org.hibernate=debug

– You could eliminate that category entirely, by commenting it out#log4j.logger.org.hibernate=info

– The main logger categories that Hibernate uses are shown in the following slide

Session 5: Introduction to Hibernate

Evaluation Copy

Page 160: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 32820120607

Fast Track to Spring 3 and Hibernate

Hibernate Logging Categories

org.hibernate.SQL: Log all SQL DML statements as they are executedorg.hibernate.type: Log all JDBC parametersorg.hibernate.tool.hbm2ddl: Log all SQL DDL statements as they are executedorg.hibernate.pretty: Log the state of all entities (max 20 entities) associated with the session at flush timeorg.hibernate.cache: Log all second-level cache activityorg.hibernate.transaction: Log transaction related activityorg.hibernate.jdbc: Log all JDBC resource acquisitionorg.hibernate.hql.ast.AST: Log HQL and SQL ASTs during query parsingorg.hibernate.secure: Log all JAAS authorization requestsorg.hibernate: Log everything (a lot of information, but very useful for troubleshooting)

Session 5: Introduction to Hibernate

Evaluation Copy

Page 161: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 32920120607

Fast Track to Spring 3 and Hibernate

Lab 5.3 – Controlling Hibernate Logging

Lab 5.3: Hibernate Logging

Evaluation Copy

Page 162: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 33020120607

Fast Track to Spring 3 and Hibernate

Lab –Hibernate Logging

Overview: In this lab you will modify the logging output that Hibernate is producing– We will enable log4j logging by including the log4j jar in our

classpath, and using a log4j.properties file– We'll start with a sample log4j.properties file that comes with

Hibernate, then customize it to get additional output that is useful for understanding and debugging Hibernate programs

Objectives:– Learn about log4j configuration, and modify the log4j logging

output of your Hibernate program

Builds on previous labs: Lab 5.2

Approximate Time: 20-25 minutes

Lab

Lab 5.3: Hibernate Logging

Evaluation Copy

Page 163: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 33120120607

Fast Track to Spring 3 and Hibernate

Copy Files

Tasks to PerformCopy the file LabSetup\Lab05.3\log4j.properties to the project's src folder– This file is based on the sample logging properties file that ships

with Hibernate

Paste the file into your project's src folder within Eclipse:– Copy the file on the file system, go the Package Explorer in

Eclipse, and paste it into the Lab05.1\src folder– Eclipse will immediately recognize the file as being in the project– If you just paste into the file system, you must refresh the project– Right click the project in Eclipse, and select Refresh, so Eclipse

picks up the files

Lab

Note that Eclipse already has a log4j jar in its runtime path– We need to include one in the project build path so the

project can configure log4j with its own properties file

Lab 5.3: Hibernate Logging

Evaluation Copy

Page 164: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 33220120607

Fast Track to Spring 3 and Hibernate

Modify the log4j.properties file

Tasks to PerformOpen log4j.properties and make the following modifications– Uncomment the following category, so that log4j will print the

SQL that Hibernate is usinglog4j.logger.org.hibernate.SQL=debug

– Modify the JDBC bind parameter output, to get more detail, so we can see exactly what values are being used in queries

– Comment out the info level line, and uncomment the trace line#log4j.logger.org.hibernate.type=info

log4j.logger.org.hibernate.type=trace

Comment out the show_sql property in hibernate.cfg.xml– The Hibernate SQL category gives us more control over this<!-- <property name="hibernate.show_sql">true</property> -->

Lab

Of course, you want to open the log4j.properties file that is inyour Eclipse project

Lab 5.3: Hibernate Logging

Evaluation Copy

Page 165: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 33320120607

Fast Track to Spring 3 and Hibernate

Run Your Program

Tasks to PerformRun your program againYou should see logging output from your program (only)– You should see more detail on the JDBC bind parameters

Try some of the other logging loggers for a few minutesOnce done, comment out the log4j.logger.org.hibernate logger– This produces a lot of output that you don't normally need

Lab

Lab 5.3: Hibernate Logging

Evaluation Copy

Page 166: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 33420120607

Fast Track to Spring 3 and Hibernate

Look at the Documentation !

Tasks to PerformGo to the Hibernate documentation Web page– http://www.hibernate.org/docs– You can look at the docs for Hibernate 3.5– Just follow the links on the page above for the needed docs

Review the Core Reference Manual– This is the main reference manual for Hibernate

Review the JavaDocs:– This is the documentation for the Hibernate Java API

Browse these and keep them handy – They're very useful !

Lab

STOP

Lab 5.3: Hibernate Logging

Evaluation Copy

Page 167: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 33520120607

Fast Track to Spring 3 and Hibernate

Review Questions

Why do we need a tool like Hibernate anyway?

What is the main purpose of Hibernate?

What does the hibernate.cfg.xml file do?

What does the Configuration class do? SessionFactory?

How do you map an entity class to the database

What is the id property of an entity class?– How is it initialized?

How do you actually work with entity instances to store or load them to/from the database?

Session 5: Introduction to Hibernate

Evaluation Copy

Page 168: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 33620120607

Fast Track to Spring 3 and Hibernate

Lesson Summary

Hibernate addresses the problem of Object-Relational Mapping (ORM) which arises from the different models used in OO-programs and relational databases– It is designed to provide a flexible, powerful, fully featured ORM

framework that relieves the developer of 95% of common data persistence related programming

The hibernate.cfg.xml file is used to configure the connection to the database, and other Hibernate properties

The Configuration class is used to specify what configuration files are used to start Hibernate up, and to create a SessionFactory

A SessionFactory represents a configuration for a particular database, and is used to create Session instances

Session 5: Introduction to Hibernate

Evaluation Copy

Page 169: Spring3-Hibernate Sessions 20120607 - ITCourseware · Spring / Hibernate Integration _____ 347 Spring Support for Hibernate ... 20120607 Copyright © 2004-12, LearningPatterns Inc.

Notes:

Copyright © 2004-12 LearningPatterns Inc. All rights reserved. 33720120607

Fast Track to Spring 3 and Hibernate

Lesson Summary

An entity class is mapped to the database via metadata– Either an XML configuration file, or with annotations

All entity classes have to have a primary key– This is usually stored in the id property of an entity class?– Hibernate has flexible support for common situations like

surrogate keys generated in the database

A Session instance is used to interact with the database when working with entity instances– It has methods to load, store, update, and etc. instances– The API for interacting with the database is encapsulated in theSession interface

Session 5: Introduction to Hibernate

Evaluation Copy