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 J ava/J ava 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 E v a l u a t i o n
C o p y
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 E v a l u a t i o n
C o p y
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 J DBC 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 E v a l u a t i o n
C o p y
20120607 Copyright 2004-12, LearningPatterns Inc. All rights reserved iv
The J dbcTemplate Class __________________________________________________________ 213 The JdbcDaoSupport Class________________________________________________________ 214 DataSources____________________________________________________________________ 215 Spring Jdbc Exception Hierarchy ___________________________________________________ 216 DAO Based on Spring Classes _____________________________________________________ 217 An Example of Using J dbcDaoSupport_______________________________________________ 218 Configuring a DataSource_________________________________________________________ 219 Example Using the DAO__________________________________________________________ 220 Looking up a DataSource in J NDI___________________________________________________ 221 Building a DAO Without the Support Class___________________________________________ 222 Lab 4.1 Spring JDBC________________________________________________________ 223 Queries and Updates_______________________________________________________ 231 Querying With J dbcTemplate______________________________________________________ 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 SimpleJ dbcTemplate 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 E v a l u a t i o n
C o p y
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 J ava - 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 E v a l u a t i o n
C o p y
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 J TA 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 E v a l u a t i o n
C o p y
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 J ava Class _____________________________________________________ 487 Version Element in Mapping File___________________________________________________ 488 Automatic Version Maintenance____________________________________________________ 489 Optimistic Locking Example_______________________________________________________ 490 Updating a Detached Instance______________________________________________________ 491 E v a l u a t i o n
C o p y
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 J ava Collection Type___________________________________________________ 519 Using the J ava 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 E v a l u a t i o n
C o p y
20120607 Copyright 2004-12, LearningPatterns Inc. All rights reserved ix
FETCH J OIN 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 J oined: 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 J ava 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 E v a l u a t i o n
C o p y
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 J ava Persistence API Overview_____________________________________________________ 647 J ava Persistence Environments _____________________________________________________ 648 Hibernate and J PA_______________________________________________________________ 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 J ava Persistence Query Language___________________________________________________ 668 Executing a Query_______________________________________________________________ 669 WHERE Clause and Query Parameters_______________________________________________ 671 Named Queries _________________________________________________________________ 672 Version Property in J ava Class _____________________________________________________ 674 Versioned Class and Detached Objects_______________________________________________ 675 Relationships _____________________________________________________________ 676 J PA 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
E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 1 20120607 Fast Track to Spring 3 and Hibernate Fast Track to Spring 3 and Hibernate The J ava Developer Education Series LearningPatterns Inc. Introduction E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 2 20120607 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 J ava 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 3 20120607 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 J dbc 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 J ava 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 J ava Persistence API Introduction E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 4 20120607 Fast Track to Spring 3 and Hibernate Workshop Agenda Session 1: Introduction to Spring Session 2: More About Bean Properties Session 3: The Spring Container and API Session 4: Database Access With Spring Session 5: Introduction to Hibernate Session 6: Spring / Hibernate Integration Session 7: Updates and Queries Session 8: Transactions Session 9: Hibernate Lifecycle Session 10: Relationships Session 11: Spring and the Web Session 12: Hibernate Additional Topics Session 13: Hibernate and the JPA Introduction E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 5 20120607 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 below package 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 6 20120607 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 - J avaTunes, an online music store The labs are contained directly in the course book, and have detailed instructions on what needs to be done The course includes setup zip files that contain skeleton 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 7 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 8 20120607 Fast Track to Spring 3 and Hibernate Session 1: Introduction to Spring Overview Spring Introduction Dependency Injection Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 9 20120607 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 J ava Learn how Spring uses configuration information and Dependency Injection (DI) to manage the beans (objects) in an application Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 10 20120607 Fast Track to Spring 3 and Hibernate Overview Overview Spring Introduction Dependency Injection Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 11 20120607 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 J ava/J ava EE (Enterprise Edition) has many capabilities to build these enterprise applications J ava SE defines basic building blocks like J ava primitives and core libraries like Collections J ava EE defines a large suite of technologies for building enterprise applications - e.g. EJ B and J DBC However, there are shortcomings to the J ava solution There really is no formal definition of an enterprise application Typically 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 J ava applications share some of the requirements that we are outlining here Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 12 20120607 Fast Track to Spring 3 and Hibernate Shortcomings of Java/Java EE J ava/J ava EE can have significant shortcomings, including: Basic J ava has little support for managing the lifecycle of your objects and the dependencies between them Managing large numbers of objects requires significant effort The J ava EE platform is quite large and requires a fairly heavyweight application server Even if you are not using most of the capabilities of J ava EE, the application server generally supports all of them J ava EE has been difficult to use, and intrusive in its design For example, using Enterprise J avaBeans (EJ B) required you to write business classes that implemented a specific API This is changing, and newer releases, such as EJ B 3, are less intrusive Though rich in functionality, due to its complexity, and the complexity of the systems being written, J ava / J ava EE can have a 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 objects The newer J ava and J ava EE technologies have started to address the ease of use issue The use of J ava annotations (introduced in J ava 5), new versions of existing technologies (such as EJ B 3), and completely new technologies such as J avaServer Faces (J SF) have made it significantly easier to use J ava Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 13 20120607 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 need It includes the following capabilities A Dependency Injection (Inversion of Control) / container to manage objects and their dependencies A DAO package that abstracts J DCB and simplifies its use An ORM package providing integration with technologies such as Hibernate and J PA (J ava 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 Object ORM stands for Object-Relational Mapping Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 14 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 15 20120607 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 a separate download from the regular Spring distribution Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 16 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 17 20120607 Fast Track to Spring 3 and Hibernate Lab 1.1 Setting Up the Environment Lab 1.1: Setting Up the Environment E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 18 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 19 20120607 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 them An example appears below Tasks to Perform Look at these instructions, and notice the different look of the box 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 20 20120607 Fast Track to Spring 3 and Hibernate Setup Environment Tasks to Perform Make sure that Spring 3.0 is installed likely in a directory such as C:\spring-framework-3.0.2.RELEASE If it's been installed in a different directory, you'll need to modify the instructions in the lab to refer to your install directory If it isn't installed, you'll need to download it (from http://www.springframework.org/download) and unzip it Make sure that you have J ava (version 5 or later) installed J ava 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 J ava 5 or later for this course, as Spring 3 depends on J ava 5 annotations Earlier versions of Spring were usable with older J ava versions, but Spring 3 added a dependency on J ava 5 In general, J ava 5 is becoming more of a requirement, as frameworks adopt its technologies Lab 1.1: Setting Up the Environment E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 21 20120607 Fast Track to Spring 3 and Hibernate Extract the Lab Setup Zip File To set up the labs, you'll need the course setup zip file * It has a name like: LabSetup_Spring3-Hibernate_Eclipse_20120607.zip Our base working directory for this course will be : C:\StudentWork\Spring This directory will be created when we extract the Setup zip It includes a directory structure and files (e.g., J ava 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 Perform Unzip 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 given to you by your instructor Lab 1.1: Setting Up the Environment E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 22 20120607 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/ : J ava 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'veincluded 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 23 20120607 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 requirements Subsequent labs require you to do the same thing as this lab to build/run, so they include fewer detailed instructions on how to do so Lab Lab 1.1: Setting Up the Environment E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 24 20120607 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 J ava 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 25 20120607 Fast Track to Spring 3 and Hibernate Launch Eclipse Tasks to Perform To 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 26 20120607 Fast Track to Spring 3 and Hibernate Workbench and Java Perspective Tasks to Perform Close the welcome screen (Click the X - see notes) You should be in a J ava 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 J ava (as shown below left) Close the J ava EE perspective by right clicking its icon, and selecting close (as shown below right) If you were in a J ava perspective, then just remain in it Lab The Eclipse J ava EE version opens in the J ava EE perspective by default Lab 1.1: Setting Up the Environment E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 27 20120607 Fast Track to Spring 3 and Hibernate Unclutter the Workbench Tasks to Perform Let's unclutter the J ava 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 J ava perspective go to Window Save Perspective As J ava You can reset the perspective to it's defaults via Window Reset Perspective Lab 1.1: Setting Up the Environment E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 28 20120607 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 Perform Go 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 JARsagain, 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 suffix In 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 29 20120607 Fast Track to Spring 3 and Hibernate Create a Project for our Application Tasks to Perform Close any open welcome screens Create 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 J ava Settings for the project Lab To create a new J ava Project, use the menu item 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 30 20120607 Fast Track to Spring 3 and Hibernate Add the Spring Library to the ClassPath Tasks to Perform In the Java Settings dialog, click the Libraries tab * Click the Add Library button, and in the dialog that comes up, select User Library then click Next Check off Spring, then click Finish in all open dialogs * Lab If you forget to add the library in this step, you can always add it later as follows Right click on the project, select Properties, then select J ava 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 J ava 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 | J ava | 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 31 20120607 Fast Track to Spring 3 and Hibernate Running the Lab Tasks to Perform We will use Eclipse to run a skeleton program we supply in TeachMeSpring.java After 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 TechMeSpring and run it for you Lab Lab 1.1: Setting Up the Environment E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 32 20120607 Fast Track to Spring 3 and Hibernate Program Output You should see output in the Eclipse Console view showing the results of running the program Note: 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 33 20120607 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 J ava 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 34 20120607 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_folder A Perspective is basically a collection of views that are focused on a given task They provide different tools to work with the resources For example, the debugging perspective has views open for debugging, such as: Active Threads, Variables, Breakpoints, etc. There are perspectives for J ava development (J ava 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 35 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 36 20120607 Fast Track to Spring 3 and Hibernate Navigator View Shows how different resources are structured There 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 37 20120607 Fast Track to Spring 3 and Hibernate Package Explorer The Package Explorer view, is shown by default in the J ava perspective It shows the J ava element hierarchy of the J ava projects in your workbench It provides a J ava-specific view of the resources shown in the Navigator It also makes it easy to work with J ava 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 J SP file, you could click on the J SP folder and select New | File Then name the file with a .jsp extension If 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 38 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 39 20120607 Fast Track to Spring 3 and Hibernate Spring Introduction Overview Spring Introduction Dependency Injection Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 40 20120607 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 J ava Object) Spring borrowed this terminology from J avaBeans and EJ B 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 J ava 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 course Spring 2.x also added a number of J ava 5 annotations that can beused We'll cover the most important annotations Spring 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 41 20120607 Fast Track to Spring 3 and Hibernate A Basic Spring Application Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 42 20120607 Fast Track to Spring 3 and Hibernate Some Bean Classes Let's say we had the following types (your business objects) An interface, Teacher, defining the functionality we want to use A concrete class, JavaInstructor, which implemented this interface, and provided the functionality Note that Spring strongly advocates the concept of programming to interfaces (see notes) Let's look at how to manage them using Spring package com.javatunes.teach; public interface Teacher { public void teach(); } package com.javatunes.teach; public class JavaInstructor implements Teacher { public void teach() { System.out.println("BeanFactories are way cool"); } } Programming to interfaces provides many advantages 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 43 20120607 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, J MS 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 44 20120607 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 class If 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 scenarios The springGuru name follows the same convention as J ava instance field names Bean names start with a lowercase letter, and are camel cased from then on Bean names must be unique within the container the bean is hosted in Usually a bean will have a single name If it has multiple names, these are considered aliases The id attribute must follow the standard XML rules for ids There is a limited set of characters that are allowed for XML ids The 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 45 20120607 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.Resource is used to abstract access to resources (e.g. a config file) Often used to access the XML data to configure a BeanFactory FileSystemResource is a concrete implementation that allows you to easily access resources on the file system We'll show a simple example first, then more depth later Some of the responsibilities of the container are: Instantiating and configuring application objects Assembling dependencies between objects Spring also uses the ApplicationContext class to 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 J ava classpath Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 46 20120607 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 way of using Spring We will gradually introduce more capabilities throughout the course Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 47 20120607 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 generics Teacher 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 J ava classpath If beans.xml was on the classpath, then you could access it withthe following code Resource 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 48 20120607 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 E v a l u a t i o n
C o p y Notes: Some BeanFactory Methods boolean containsBean(String): returns true if BeanFactory contains 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 J ava generics (see notes) and is preferred Object getBean(String): old style non generics version Requires cast Class getType(String name): returns the Class of the bean with the given name boolean isSingleton(String): determines whether or not the named bean is a singleton String[] getAliases(String): Return the aliases for the given bean name, if any There 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 found isSingleton(String) throws NoSuchBeanDefinitionException if bean can't be found The 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. 49 20120607 Fast Track to Spring 3 and Hibernate Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 50 20120607 Fast Track to Spring 3 and Hibernate Lab 1.2 Hello Spring World Lab 1.2: Hello Spring World E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 51 20120607 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 different parts of a Spring application Accordingly, the program is as simple as we can make it It mirrors the code already shown in the previous section In later labs, we'll work with more complex applications Lab 1.2: Hello Spring World E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 52 20120607 Fast Track to Spring 3 and Hibernate Writing and Configuring a Bean in Spring Tasks to Perform Continue to work in the Lab01.1 project Open up the JavaInstructor.java file The class is in the com.javatunes.teach package, which means the file is in src\com\javatunes\teach Make sure that JavaInstructor implements the Teacher interface (in file Teacher.java) Remember that we code to interfaces to decouple us from a specific implementation Open up the src/beans.xml file Finish up the declaration of the <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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 53 20120607 Fast Track to Spring 3 and Hibernate Using a Bean in a Program Tasks to Perform Open up TeachMeSpring.java, look for the TODO comments, and add in the following code First, create a FileSystemResource to read src/beans.xml Next, create a BeanFactory with the resource above Next, look up the springGuru bean from the BeanFactory Finally call teach() on the springGuru bean Make sure you have no compilation errors in your code Run 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 54 20120607 Fast Track to Spring 3 and Hibernate Logging and Additional Things (Optional) We've provided a log4j.properties file in the src directory This configures some of the logging that Spring will do You can reduce the logging output by opening this file, and changing the INFO to WARN at the top line of the file: log4j.rootLogger=WARN, stdout You can increase the logging by using DEBUG instead Other things to try Try looking up the bean by a different name what happens? Try casting the bean you look up to a JavaInstructor instead of a Teacher Does this work? Is it a good idea? Change your code back to your original 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 POJ Os, 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 55 20120607 Fast Track to Spring 3 and Hibernate Dependencies and Dependency Injection Overview Spring Introduction Dependency Injection Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 56 20120607 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 createan instance of Object B and use it Object A is highly coupled to, and directly dependent on, Object B Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 57 20120607 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 J ava 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 J ava code examples for brevity Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 58 20120607 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 J ava 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 them We'll soon look at Spring's Dependency Injection which makes this design strategy even easier to use We talk of modules here, which in J ava are basically reflected as dependencies between different classes Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 59 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 60 20120607 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 SpringCourseBook in 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 61 20120607 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 POJ O 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 container will 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 62 20120607 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 springBook The 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 instance The <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 later The 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 useand 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 63 20120607 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 shown public 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 DI Note 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 container Note 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 64 20120607 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 J Unit 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 65 20120607 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 - TeachMeSpring only coupled to Teacher JavaInstructor only coupled to InfoSource J avaInstructor SpringCourseBook InfoSource <<interface>> creates J avaInstructor SpringCourseBook TeachMeSpring implements creates InfoSource <<interface>> TeachMeSpring Teacher <<interface>> J avaInstructor 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 66 20120607 Fast Track to Spring 3 and Hibernate Lab 1.3 Dependency Injection Lab 1.3: Dependency Injection E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 67 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 68 20120607 Fast Track to Spring 3 and Hibernate Writing and Configuring a Bean in Spring Tasks to Perform Continue to work in the Lab01.1 project Open 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() method We 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 69 20120607 Fast Track to Spring 3 and Hibernate Using a Bean in a Program Tasks to Perform Open 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 JavaInstructor dependency on SpringCourseBook is completely hidden JavaInstructor is decoupled from SpringCourseBook Lab Lab 1.3: Dependency Injection E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 70 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 71 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 72 20120607 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 own MVC 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 J ava objects in your program. It supplies many of the important capabilities of J ava EE in a less complex and lighter weight manner Session 1: Introduction to Spring E v a l u a t i o n
C o p y Notes: Copyright 2007-10 LearningPatterns Inc. All rights reserved. 73 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 252 20120607 Fast Track to Spring 3 and Hibernate Session 5: Introduction to Hibernate Hibernate Overview Using Hibernate Mapping a Simple Class Logging Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 253 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 254 20120607 Fast Track to Spring 3 and Hibernate Hibernate Overview Hibernate Overview Using Hibernate Mapping a Simple Class Logging Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 255 20120607 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 to store 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 J ava, 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 256 20120607 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 concepts Relational 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 257 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 258 20120607 Fast Track to Spring 3 and Hibernate Hibernate Overview Open Source, ORM framework for J ava 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 J ava 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 J ava 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 J ava classes to database tables (and from J ava data types to SQL data types), but also provides data queryand retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and J DBC. 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 J ava-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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 259 20120607 Fast Track to Spring 3 and Hibernate Hibernate Benefits Simplicity and flexibility POJ O based ! ORM is completely metadata driven (annotations or XML) No need to write J DBC code Common defaults that allow metadata to be minimized Persistence API is totally separate from entity classes Can be used in J ava 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 260 20120607 Fast Track to Spring 3 and Hibernate Hibernate Environments Can be used in J ava SE or J ava EE programs It is packaged as a set of jar files Only minor configuration and programming differences between using it in a J ava SE and J ava EE environment The J ava Persistence API (J PA) derived a lot of it's structure from Hibernate J PA is a required part of J ava EE 5, and uses annotations to specify mapping metadata about persistent classes Hibernate supports the standard J PA annotations, in addition to defining additional ones of its own Using the J PA annotations with Hibernate gives a smooth migration path to standard J ava Persistence Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 261 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 262 20120607 Fast Track to Spring 3 and Hibernate More Detailed Architecture In this scenario, the application manages some details itself Application manages J DBC connections and transactions Uses minimal subset of Hibernate API This can be considered Hibernate "Lite" Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 263 20120607 Fast Track to Spring 3 and Hibernate More Detailed Architecture In this scenario, the app is abstracted away from J DBC/J TA 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 264 20120607 Fast Track to Spring 3 and Hibernate Using Hibernate Hibernate Overview Using Hibernate Mapping a Simple Class Logging Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 265 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 266 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 267 20120607 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 J ava 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 268 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 269 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 270 20120607 Fast Track to Spring 3 and Hibernate SessionFactory Configuration Needs to have the usual database information Database J DBC 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 271 20120607 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 J DBC 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 J NDI name hibernate.jndi.url, hibernate.jndi.class: J NDI 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 for J DBC 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 more Hibernate 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 schemaDDL to the database when the SessionFactory is created. (validate | update | create | create-drop) Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 272 20120607 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 J DBC connection The dialect property element specifies the particular SQL variant Hibernate generates. If you're working in a J 2EE environment, there are properties that allow you to specify a datasource J NDI 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 J DBC connection pool, which we also have to configure The Hibernate distribution contains several open source J DBC 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 J DBC pooling software [Hibernate 3.2.2 Reference Documentation, Section 1.2.3] Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 273 20120607 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 J ava 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 thefile 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 Configurationinterface has methods that allow you to do the same things you can do with a configuration file Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 274 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 275 20120607 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 J DBC 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 thereare no open sessions before calling close() on the SessionFactory The 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 276 20120607 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 J DBC 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 transaction Session 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 277 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 278 20120607 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 J ava 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 J DBC driver SQLExceptions are always wrapped by instances of JDBCException There are many, more specific, subclasses of HibernateException Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 279 20120607 Fast Track to Spring 3 and Hibernate Lab 5.1 Setting up Hibernate Lab 5.1: Setting up Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 280 20120607 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 J DBC labs Objectives: Configure hibernate and write a simple hibernate application Builds on previous labs: None Approximate 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 281 20120607 Fast Track to Spring 3 and Hibernate Create Hibernate User Library Tasks to Perform Go 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.RELEASE As 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 Springlibrary in the User Libraries dialog, click the Add External JARsbutton, 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 labs Hibernate 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 282 20120607 Fast Track to Spring 3 and Hibernate Create a Project for our Application Tasks to Perform Close any open welcome screens Create 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 J ava Settings for the project Lab To create a new J ava Project, use the menu item 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 283 20120607 Fast Track to Spring 3 and Hibernate Add the Hibernate/Spring Libraries Tasks to Perform In the Java Settings dialog, click the Libraries tab * Click the Add Library button, and in the dialog that comes up, select User Library then click Next Check 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 J ava 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 J ava 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 | J ava | 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 284 20120607 Fast Track to Spring 3 and Hibernate Finish hibernate.cfg.xml Tasks to Perform In 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/J avaTunesDB 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 285 20120607 Fast Track to Spring 3 and Hibernate Create a TestClass Tasks to Perform Test 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 J ava 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 286 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 287 20120607 Fast Track to Spring 3 and Hibernate Running Your Application Tasks to Perform After 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 288 20120607 Fast Track to Spring 3 and Hibernate Testing your Application If everything is set up correctly, the program should run You 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 289 20120607 Fast Track to Spring 3 and Hibernate Debugging Problems Tasks to Perform If 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 290 20120607 Fast Track to Spring 3 and Hibernate Mapping a Simple Class Hibernate Overview Using Hibernate Mapping a Simple Class Logging Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 291 20120607 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 J ava Persistence 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 J ava 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 292 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 293 20120607 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 id private 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 294 20120607 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 J avaBean 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 295 20120607 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: J ava 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 themoff 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 296 20120607 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 your text 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, but first 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 297 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 298 20120607 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 J ava 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 J ava level. In these cases, you should provide an explicit arbitrary name for the entity with the entity-name attribute Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 299 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 300 20120607 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 J avaBeans-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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 301 20120607 Fast Track to Spring 3 and Hibernate More About Primary Keys Hibernate requires that every entity have a primary key J ust 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 ways Hibernate has extensive support for dealing with primary keys For surrogate, generated keys, and for natural keys Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 302 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 303 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 304 20120607 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 J ava 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 J ava Date, Hibernate can't really tell if it should map to a SQL date, timestamp, or time column, so we specified it in 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 J ava type system to the SQL/database type 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 J DK 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 305 20120607 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 J ava primitives or wrapper classes to appropriate (vendor-specific) SQL column types. boolean, yes_no and true_false are all alternative encodings for a J ava 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 TIMESTAMP and DATE (or equivalent). big_decimal java.math.BigDecimal to NUMERIC (or Oracle NUMBER). Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 306 20120607 Fast Track to Spring 3 and Hibernate Field Access or Property Access By default, the persistence runtime will access the persistent fields using J avaBean 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. [J PA Specification, 2006, sec. 2.1.1] Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 307 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 308 20120607 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 POJ Os 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 309 20120607 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 actuallyhit the database until you invoke a method of the proxy. This behaviour is very useful if you wish to create an association toan 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 310 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 311 20120607 Fast Track to Spring 3 and Hibernate Lab 5.2 Creating a Mapping File Lab 5.2: Creating a Mapping File E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 312 20120607 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 J ava class the MusicItem class This is a simple class that has J avaBean 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 313 20120607 Fast Track to Spring 3 and Hibernate The MusicItem Class com.javatunes.persist.MusicItem A J avaBean-style value class that represents a CD, that has the following public methods to access its attributes public Long getId() // DB Primary Key public String getNum() // CD Number public 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 314 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 315 20120607 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 BIGINT ITEM_ID (PK) VARCHAR Num VARCHAR Title VARCHAR Artist DATE ReleaseDate DECIMAL ListPrice DECIMAL Price 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 Class item_id 21 num CD521 title Music artist Madonna releaseDate 2002-02-27 listPrice 14.99 price 11.97 Item Table Lab Notice how we map each Item table column to an MusicItem member variable: column name (SQL) -> variable name (J ava) column type (SQL) -> variable type (J ava) Lab 5.2: Creating a Mapping File E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 316 20120607 Fast Track to Spring 3 and Hibernate Create a Mapping File Tasks to Perform Open the file src/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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 317 20120607 Fast Track to Spring 3 and Hibernate Add the Mapping to the Configuration Tasks to Perform Add 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 318 20120607 Fast Track to Spring 3 and Hibernate Retrieve a Persistent Entity Tasks to Perform Once 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 it Run the program and check your output That's it no mess, no fuss, no J DBC 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 319 20120607 Fast Track to Spring 3 and Hibernate [Optional] Auto Completion in Eclipse Tasks to Perform Go 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 320 20120607 Fast Track to Spring 3 and Hibernate [Optional] Design Mode for Config files Tasks to Perform Notice 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 321 20120607 Fast Track to Spring 3 and Hibernate Logging Hibernate Overview Using Hibernate Mapping a Simple Class Logging Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 322 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 323 20120607 Fast Track to Spring 3 and Hibernate Simple Logging Facade for Java - SLF4J Hibernate 3.3+ uses SLF4J to do its logging SLF4J can direct your logging output to several logging frameworks depending on your chosen binding NOP, Simple, log4j version 1.2, J DK 1.4 logging, J CL 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 inthe 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 J DK1.4 logging (if running under J DK1.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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 324 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 325 20120607 Fast Track to Spring 3 and Hibernate Hibernate log4j.properties file The Hibernate distribution ships with a sample log4j.properties file which includes entries for the major loggers that Hibernate writes 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 making it unreadable. It is an essential troubleshooting device." Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 326 20120607 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.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 327 20120607 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 output log4j.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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 328 20120607 Fast Track to Spring 3 and Hibernate Hibernate Logging Categories org.hibernate.SQL: Log all SQL DML statements as they are executed org.hibernate.type: Log all J DBC parameters org.hibernate.tool.hbm2ddl: Log all SQL DDL statements as they are executed org.hibernate.pretty: Log the state of all entities (max 20 entities) associated with the session at flush time org.hibernate.cache: Log all second-level cache activity org.hibernate.transaction: Log transaction related activity org.hibernate.jdbc: Log all J DBC resource acquisition org.hibernate.hql.ast.AST: Log HQL and SQL ASTs during query parsing org.hibernate.secure: Log all J AAS authorization requests org.hibernate: Log everything (a lot of information, but very useful for troubleshooting) Session 5: Introduction to Hibernate E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 329 20120607 Fast Track to Spring 3 and Hibernate Lab 5.3 Controlling Hibernate Logging Lab 5.3: Hibernate Logging E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 330 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 331 20120607 Fast Track to Spring 3 and Hibernate Copy Files Tasks to Perform Copy 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 332 20120607 Fast Track to Spring 3 and Hibernate Modify the log4j.properties file Tasks to Perform Open log4j.properties and make the following modifications Uncomment the following category, so that log4j will print the SQL that Hibernate is using log4j.logger.org.hibernate.SQL=debug Modify the J DBC 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 in your Eclipse project Lab 5.3: Hibernate Logging E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 333 20120607 Fast Track to Spring 3 and Hibernate Run Your Program Tasks to Perform Run your program again You should see logging output from your program (only) You should see more detail on the J DBC bind parameters Try some of the other logging loggers for a few minutes Once 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 334 20120607 Fast Track to Spring 3 and Hibernate Look at the Documentation ! Tasks to Perform Go to the Hibernate documentation Web page http://www.hibernate.org/docs You can look at the docs for Hibernate 3.5 J ust 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 J ava API Browse these and keep them handy They're very useful ! Lab STOP Lab 5.3: Hibernate Logging E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 335 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 336 20120607 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 E v a l u a t i o n
C o p y Notes: Copyright 2004-12 LearningPatterns Inc. All rights reserved. 337 20120607 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 the Session interface Session 5: Introduction to Hibernate E v a l u a t i o n