92
20101220 Copyright © 2005-10, LearningPatterns Inc. All rights reserved i Table of Contents - Fast Track to Hibernate 3 Fast Track to Hibernate__________________________________________________ 1 Workshop Overview and Objectives___________________________________________________ 2 Workshop Agenda _________________________________________________________________ 3 Release Level_____________________________________________________________________ 4 Typographic Conventions ___________________________________________________________ 5 Labs ____________________________________________________________________________ 6 Session 1: Introduction to Hibernate _______________________________________ 7 Lesson Objectives _________________________________________________________________ 8 Hibernate Overview _________________________________________________________ 9 The Issues with Persistence Layers ___________________________________________________ 10 Object-Relational Mapping (ORM) Issues _____________________________________________ 11 Issues with JDBC Alone ___________________________________________________________ 12 Hibernate Overview_______________________________________________________________ 13 Hibernate Benefits ________________________________________________________________ 14 Hibernate Environments ___________________________________________________________ 15 Hibernate Architecture ____________________________________________________________ 16 More Detailed Architecture _________________________________________________________ 17 More Detailed Architecture _________________________________________________________ 18 Using Hibernate ___________________________________________________________ 19 Acquiring Hibernate ______________________________________________________________ 20 Using Hibernate__________________________________________________________________ 21 Configuring Hibernate_____________________________________________________________ 22 Sample hibernate.cfg.xml __________________________________________________________ 23 hibernate.cfg.xml Elements _________________________________________________________ 24 SessionFactory Configuration _______________________________________________________ 25 SessionFactory Configuration Properties ______________________________________________ 26 Example Properties for PostgresSQL _________________________________________________ 27 The Configuration Class ___________________________________________________________ 28 The SessionFactory Interface _______________________________________________________ 29 SessionFactory API _______________________________________________________________ 30 The Session Interface _____________________________________________________________ 31 Sessions and Transactions __________________________________________________________ 32 A Basic Hibernate Program Example _________________________________________________ 33 Lab 1.1 – Setting up Hibernate___________________________________________________ 34 Mapping a Simple Class _____________________________________________________ 63 Persistent Entity Classes ___________________________________________________________ 64 Persistent Classes_________________________________________________________________ 65 An Example Persistent Class________________________________________________________ 66 The Event Class__________________________________________________________________ 67 The id Property __________________________________________________________________ 68 The Hibernate Mapping File ________________________________________________________ 69 The <hibernate-mapping> Element___________________________________________________ 70 The <class> Element ______________________________________________________________ 71 The EVENTS Table ______________________________________________________________ 72 Mapping the id Property with <id> ___________________________________________________ 73 More About Primary Keys _________________________________________________________ 74 Generating the id Value____________________________________________________________ 75 Mapping Properties with <property>__________________________________________________ 76 Hibernate Mapping Types __________________________________________________________ 77

Table of Contents - Fast Track to Hibernate 3 · Table of Contents - Fast Track to Hibernate 3 ... to

Embed Size (px)

Citation preview

20101220 Copyright © 2005-10, LearningPatterns Inc. All rights reserved i

Table of Contents - Fast Track to Hibernate 3

Fast Track to Hibernate__________________________________________________ 1 Workshop Overview and Objectives ___________________________________________________ 2 Workshop Agenda_________________________________________________________________ 3 Release Level_____________________________________________________________________ 4 Typographic Conventions ___________________________________________________________ 5 Labs ____________________________________________________________________________ 6

Session 1: Introduction to Hibernate _______________________________________ 7 Lesson Objectives _________________________________________________________________ 8

Hibernate Overview _________________________________________________________ 9 The Issues with Persistence Layers ___________________________________________________ 10 Object-Relational Mapping (ORM) Issues _____________________________________________ 11 Issues with JDBC Alone ___________________________________________________________ 12 Hibernate Overview_______________________________________________________________ 13 Hibernate Benefits ________________________________________________________________ 14 Hibernate Environments ___________________________________________________________ 15 Hibernate Architecture ____________________________________________________________ 16 More Detailed Architecture_________________________________________________________ 17 More Detailed Architecture_________________________________________________________ 18

Using Hibernate ___________________________________________________________ 19 Acquiring Hibernate ______________________________________________________________ 20 Using Hibernate__________________________________________________________________ 21 Configuring Hibernate_____________________________________________________________ 22 Sample hibernate.cfg.xml __________________________________________________________ 23 hibernate.cfg.xml Elements _________________________________________________________ 24 SessionFactory Configuration _______________________________________________________ 25 SessionFactory Configuration Properties ______________________________________________ 26 Example Properties for PostgresSQL _________________________________________________ 27 The Configuration Class ___________________________________________________________ 28 The SessionFactory Interface _______________________________________________________ 29 SessionFactory API _______________________________________________________________ 30 The Session Interface _____________________________________________________________ 31 Sessions and Transactions __________________________________________________________ 32 A Basic Hibernate Program Example _________________________________________________ 33

Lab 1.1 – Setting up Hibernate___________________________________________________ 34 Mapping a Simple Class_____________________________________________________ 63

Persistent Entity Classes ___________________________________________________________ 64 Persistent Classes_________________________________________________________________ 65 An Example Persistent Class________________________________________________________ 66 The Event Class__________________________________________________________________ 67 The id Property __________________________________________________________________ 68 The Hibernate Mapping File ________________________________________________________ 69 The <hibernate-mapping> Element ___________________________________________________ 70 The <class> Element ______________________________________________________________ 71 The EVENTS Table ______________________________________________________________ 72 Mapping the id Property with <id> ___________________________________________________ 73 More About Primary Keys _________________________________________________________ 74 Generating the id Value____________________________________________________________ 75 Mapping Properties with <property>__________________________________________________ 76 Hibernate Mapping Types __________________________________________________________ 77

20101220 Copyright © 2005-10, LearningPatterns Inc. All rights reserved ii

Common Hibernate Type Mappings __________________________________________________ 78 Field Access or Property Access _____________________________________________________ 79 The Mapping File ________________________________________________________________ 80 Hibernate Sessions________________________________________________________________ 81 The Session Interface _____________________________________________________________ 82 Retrieving Persistent Objects________________________________________________________ 83

Lab 1.2 – Creating a Mapping File _______________________________________________ 84 Logging __________________________________________________________________ 94

hibernate.show_sql _______________________________________________________________ 95 Simple Logging Facade for Java - SLF4J ______________________________________________ 96 Apache Log4J ___________________________________________________________________ 97 Hibernate log4j.properties file_______________________________________________________ 98 The log4j.properties file ___________________________________________________________ 99 Modifying log4j.properties for Hibernate _____________________________________________ 100 Hibernate Logging Categories______________________________________________________ 101

Lab 1.3 – Controlling Hibernate Logging _________________________________________ 102 Review Questions _______________________________________________________________ 108 Lesson Summary ________________________________________________________________ 109 Lesson Summary ________________________________________________________________ 110

Appendix - log4j __________________________________________________________ 111 Apache log4j ___________________________________________________________________ 112 log4j Loggers___________________________________________________________________ 113 Logger Hierarchy________________________________________________________________ 114 Logger Levels __________________________________________________________________ 115 Appenders _____________________________________________________________________ 116 Appender Additivity _____________________________________________________________ 117 Additivity Example ______________________________________________________________ 118 Layout ________________________________________________________________________ 119 log4j Configuration File __________________________________________________________ 120 Sample log4j.properties Configuration File____________________________________________ 121 Sample of Creating Output from Logger______________________________________________ 122 PatternLayout __________________________________________________________________ 123 Multiple Layouts ________________________________________________________________ 124 Some log4j Appenders____________________________________________________________ 125

Session 2: Updates and Queries _________________________________________ 126 Lesson Objectives _______________________________________________________________ 127

Inserting and Updating ____________________________________________________ 128 Inserting Instances_______________________________________________________________ 129 Inserting Instance Example ________________________________________________________ 130 Modifying a Persistent Instance_____________________________________________________ 131 Deleting an Instance _____________________________________________________________ 132

Lab 2.1 – Inserting and Modifying_______________________________________________ 133 Hibernate Query Language ________________________________________________________ 138 HQL Basics ____________________________________________________________________ 139 Executing a Query _______________________________________________________________ 140 Executing a Query _______________________________________________________________ 141 Executing a Query _______________________________________________________________ 142 Other Common Query Methods ____________________________________________________ 143 Where Clause / Restriction ________________________________________________________ 144 HQL Operators and Expressions ____________________________________________________ 145 Query Parameters _______________________________________________________________ 146 Using Query Parameters __________________________________________________________ 147 Named Queries _________________________________________________________________ 148

20101220 Copyright © 2005-10, LearningPatterns Inc. All rights reserved iii

Projection Queries _______________________________________________________________ 149 Projection Queries Returning Tuples_________________________________________________ 150 Additional Query Capabilities ______________________________________________________ 151 Aggregate Functions _____________________________________________________________ 152

Lab 2.2 – Basic Querying ______________________________________________________ 153 Review Questions _______________________________________________________________ 158 Lesson Summary ________________________________________________________________ 159 Lesson Summary ________________________________________________________________ 160

Session 3: Lifecycle ___________________________________________________ 161 Lesson Objectives _______________________________________________________________ 162

Transaction Definition _____________________________________________________ 163 Transaction Overview ____________________________________________________________ 164 Transaction Overview ____________________________________________________________ 165 Transaction Lifecycle ____________________________________________________________ 166 Transactions Modularize Systems ___________________________________________________ 167 Transactions Clarify Systems ______________________________________________________ 168

Hibernate and Transactions ________________________________________________ 169 Hibernate and Transactions ________________________________________________________ 170 Hibernate Transaction Demarcation _________________________________________________ 171 Working With Transactions________________________________________________________ 172 The Hibernate Transaction API_____________________________________________________ 173 Working in a Managed Environment ________________________________________________ 174 Working in a Managed Environment ________________________________________________ 175

The Persistence Lifecycle ___________________________________________________ 176 The Persistence Lifecycle _________________________________________________________ 177 Hibernate Object States ___________________________________________________________ 178 Transient and Persistent State ______________________________________________________ 179 Detached and Removed State ______________________________________________________ 180 Hibernate Object States and Transitions ______________________________________________ 181 The Persistence Context __________________________________________________________ 182 Session / Persistence Context Lifespan _______________________________________________ 183 Session-per-request ______________________________________________________________ 184 Session Propagation______________________________________________________________ 185 First – Acquiring a SessionFactory Instance ___________________________________________ 186 Contextual Session ______________________________________________________________ 187 Using Contextual Sessions ________________________________________________________ 188 What is the "Current" Context______________________________________________________ 189 Contextual Session Scope _________________________________________________________ 190 The Persistence Context as Cache ___________________________________________________ 191 Synchronization To the Database ___________________________________________________ 192 Flushing the session______________________________________________________________ 193 Flushing the Session _____________________________________________________________ 194 Persistence Context and Object Identity ______________________________________________ 195 Yes, It's Complicated_____________________________________________________________ 196

Lab 3.1 – Using Contextual Sessions _____________________________________________ 197 Versioning and Optimistic Locking __________________________________________ 202

Detached Objects and Optimistic Locking ____________________________________________ 203 Using a Detached Instance ________________________________________________________ 204 Using a Detached Instance Example _________________________________________________ 205 Optimistic Locking and Versioning__________________________________________________ 206 Version Property in Java Class _____________________________________________________ 207 Version Element in Mapping File ___________________________________________________ 208 Automatic Version Maintenance ____________________________________________________ 209

20101220 Copyright © 2005-10, LearningPatterns Inc. All rights reserved iv

Optimistic Locking Example_______________________________________________________ 210 Updating a Detached Instance ______________________________________________________ 211 Session.saveOrUpdate() __________________________________________________________ 212 The unsaved-value Attribute _______________________________________________________ 213 The unsaved-value Attribute _______________________________________________________ 214 Locking Objects_________________________________________________________________ 215 Lock Modes____________________________________________________________________ 216 Using Session.lock() Example______________________________________________________ 217

Lab 3.2 – Versioning __________________________________________________________ 218 Review Questions _______________________________________________________________ 221 Lesson Summary ________________________________________________________________ 222

Session 4: Relationships _______________________________________________ 225 Lesson Objectives _______________________________________________________________ 226

Relationships Overview ____________________________________________________ 227 Object Relationships _____________________________________________________________ 228 Characteristics of Relationships ____________________________________________________ 229 Directionality___________________________________________________________________ 230 Directionality___________________________________________________________________ 231 Characteristics of Relationships ____________________________________________________ 232

Collections of Value Objects ________________________________________________ 233 Collections of Values ____________________________________________________________ 234 Modeling a Set of Values _________________________________________________________ 235 Mapping the Set of Values ________________________________________________________ 236 Using a Set of Values ____________________________________________________________ 237 More on the Java Collection Type___________________________________________________ 238 Using the Java Collection Types ____________________________________________________ 239 Modeling a List of Values _________________________________________________________ 240 Mapping a List of Values _________________________________________________________ 241 Sorted and Ordered Collections_____________________________________________________ 242 Collections of Components ________________________________________________________ 243 Mapping Collections of Components ________________________________________________ 244

Lab 4.1 – Mapping a Value Set__________________________________________________ 245 Mapping Entity Relationships _______________________________________________ 249

Mappings Overview _____________________________________________________________ 250 Unidirectional Many-To-One Relationship____________________________________________ 251 The Table Structure – Many-To-One ________________________________________________ 252 Mapping the Relationship _________________________________________________________ 253 Using the Relationship ___________________________________________________________ 254 Bidirectional One-To-Many Relationship _____________________________________________ 255 Defining the One-To-Many Relationship _____________________________________________ 256 Mapping the One-To-Many Relationship _____________________________________________ 257 More on the Inverse Side__________________________________________________________ 258 Cascading Operations ____________________________________________________________ 259 Transitive Persistence ____________________________________________________________ 260 The cascade Attribute ____________________________________________________________ 261 Cascade Choices ________________________________________________________________ 262 Choosing Cascade Options ________________________________________________________ 263

Lab 4.2 – Relationships ________________________________________________________ 264 Bidirectional One-To-One Relationship ______________________________________________ 273 Bidirectional One-To-One Relationship ______________________________________________ 274 Mapping a One-To-One Relationship ________________________________________________ 275 Many-To-Many Relationship ______________________________________________________ 276 Defining Many-To-Many Relationship _______________________________________________ 277

20101220 Copyright © 2005-10, LearningPatterns Inc. All rights reserved v

Mapping Many-To-Many Relationship_______________________________________________ 278 Mapping Many-To-Many Relationship_______________________________________________ 279 Lazy and Eager Loading __________________________________________________________ 280 Queries Across Relationships ______________________________________________________ 281 OUTER and FETCH JOIN ________________________________________________________ 282 FETCH JOIN Example ___________________________________________________________ 283

Lab 4.3 – Working With Relationships ___________________________________________ 284 Mapping Inheritance ______________________________________________________ 289

Inheritance_____________________________________________________________________ 290 Entity Inheritance _______________________________________________________________ 291 Details of Entity Inheritance _______________________________________________________ 292 Single-Table Strategy ____________________________________________________________ 293 Class Definitions for Single-Table __________________________________________________ 294 Mapping for Single-Table _________________________________________________________ 295 Sample Table Entries_____________________________________________________________ 296 Single-Table: Pros and Cons _______________________________________________________ 297 Table per Subclass (Joined Subclass) ________________________________________________ 298 Mapping for Table per Subclass ____________________________________________________ 299 Sample Table Entries_____________________________________________________________ 300 Joined: Pros and Cons ____________________________________________________________ 301 Table per Concrete Class__________________________________________________________ 302

Lab 4.4 – Working With Inheritance_____________________________________________ 303 Review Questions _______________________________________________________________ 308 Review Questions _______________________________________________________________ 309 Lesson Summary ________________________________________________________________ 310 Lesson Summary ________________________________________________________________ 311 Lesson Summary ________________________________________________________________ 312

Session 5: Additional Querying Capabilities _______________________________ 313 Lesson Objectives _______________________________________________________________ 314

More on Querying_________________________________________________________ 315 Projection Queries _______________________________________________________________ 316 Aggregate Queries _______________________________________________________________ 317 Aggregate Query Examples________________________________________________________ 318 Bulk Update and Delete___________________________________________________________ 319 Executing Bulk Operations ________________________________________________________ 320 Native SQL Queries _____________________________________________________________ 321 Refining SQL Queries ____________________________________________________________ 322 Retrieving Entities with SQL Queries ________________________________________________ 323

Filters ___________________________________________________________________ 324 Hibernate Filters ________________________________________________________________ 325 Defining and Attaching Filters _____________________________________________________ 326 Using a Filter ___________________________________________________________________ 327 Mapping a Filter to a Set __________________________________________________________ 328 Collection Filters ________________________________________________________________ 329

Lab 5.1 – Filters ______________________________________________________________ 330 Criteria__________________________________________________________________ 333

Criteria Overview _______________________________________________________________ 334 A Simple Criteria Example ________________________________________________________ 335 Restrictions - Narrowing the Result Set ______________________________________________ 336 Restrictions Methods _____________________________________________________________ 337 Restrictions Example_____________________________________________________________ 338 Navigating Associations __________________________________________________________ 339 Navigating Associations __________________________________________________________ 340

20101220 Copyright © 2005-10, LearningPatterns Inc. All rights reserved vi

Eager Fetching__________________________________________________________________ 341 Query By Example ______________________________________________________________ 342 Refining the Example ____________________________________________________________ 343 Additional Capabilities ___________________________________________________________ 344

Lab 5.2 – Criteria Queries _____________________________________________________ 345 Review Questions _______________________________________________________________ 348 Lesson Summary ________________________________________________________________ 349

Session 6: Hibernate and the Java Persistence API (JPA)____________________ 351 Lesson Objectives _______________________________________________________________ 352

JPA Overview ____________________________________________________________ 353 Java Persistence API Overview_____________________________________________________ 354 Java Persistence Environments _____________________________________________________ 355 Hibernate and JPA_______________________________________________________________ 356

Mapping a Simple Class____________________________________________________ 357 Entity Classes __________________________________________________________________ 358 Event Entity Mapped with JPA _____________________________________________________ 359 The Entity Declaration____________________________________________________________ 360 The Event Class_________________________________________________________________ 361 The Id Property _________________________________________________________________ 362 Mapping Properties ______________________________________________________________ 363 Basic Mapping Types ____________________________________________________________ 364

Lab 6.1 – Mapping an Entity Class with JPA ______________________________________ 365 Entity Manager and Persistence Context ______________________________________ 369

The Entity Manager & Persistence Context ___________________________________________ 370 Persistence Unit_________________________________________________________________ 371 persistence.xml _________________________________________________________________ 372 persistence.xml Example__________________________________________________________ 373 Acquiring an EntityManager _______________________________________________________ 374 Working With Transactions________________________________________________________ 375 Retrieving Persistent Objects_______________________________________________________ 376

Lab 6.2 – Using an Entity Class _________________________________________________ 377 Inserts and Queries________________________________________________________ 380

Persisting a New Entity ___________________________________________________________ 381 Java Persistence Query Language ___________________________________________________ 382 Executing a Query _______________________________________________________________ 383 Executing a Query _______________________________________________________________ 384 WHERE Clause and Query Parameters_______________________________________________ 385 Named Queries _________________________________________________________________ 386 Named Queries _________________________________________________________________ 387 Version Property in Java Class _____________________________________________________ 388 Versioned Class and Detached Objects _______________________________________________ 389

Relationships _____________________________________________________________ 390 JPA Support for Relationships _____________________________________________________ 391 Mapping the Many-To-One Relationship _____________________________________________ 392 Mapping the One-To-Many Relationship _____________________________________________ 393 Loading and Cascading ___________________________________________________________ 394 Queries Across Relationships ______________________________________________________ 395 Inheritance_____________________________________________________________________ 396 Entity Definitions for Single-Table __________________________________________________ 397 Entity Definitions for Joined _______________________________________________________ 398 Lesson Summary ________________________________________________________________ 399

20101220 Copyright © 2005-10, LearningPatterns Inc. All rights reserved vii

Session 7: Advanced Topics_____________________________________________ 400 Lesson Objectives _______________________________________________________________ 401

Components and Multi-Table Mapping _______________________________________ 402 Component Overview ____________________________________________________________ 403 Component Example _____________________________________________________________ 404 Mapping a Component ___________________________________________________________ 405 Multi-Table Mapping ____________________________________________________________ 406 Multi Table Mapping_____________________________________________________________ 407

equals() and hashCode()____________________________________________________ 408 Defining equals() and hashCode()___________________________________________________ 409 Redefining equals() ______________________________________________________________ 410 Example of equals() and hashCode()_________________________________________________ 411

Caching _________________________________________________________________ 412 Second-Level Cache _____________________________________________________________ 413 Data Appropriate for Caching ______________________________________________________ 414 Cache Providers_________________________________________________________________ 415 Configuring Caching _____________________________________________________________ 416 Cache Configuration Example______________________________________________________ 417 Concurrency Strategies ___________________________________________________________ 418 Managing the Caches ____________________________________________________________ 419

Design Considerations _____________________________________________________ 420 Overview ______________________________________________________________________ 421 - Long Conversations - ___________________________________________________________ 422 Session-Per-Conversation (Extended Session) _________________________________________ 423 Session-Per-Conversation _________________________________________________________ 424 - Problems with Web Applications - _________________________________________________ 425 Open Session In View Pattern ______________________________________________________ 426 Open Session In View Example ____________________________________________________ 427 - Query Efficiency Techniques - ____________________________________________________ 428 Beware of n+1 Select Issue ________________________________________________________ 429 Prefetching Data in Batches _______________________________________________________ 430 Data Access Object (DAO) ________________________________________________________ 431

Hibernate Toolset _________________________________________________________ 432 Hibernate Tools Overview_________________________________________________________ 433 Important Note on Versions _______________________________________________________ 434 Optional - Hibernate Tools ________________________________________________________ 435 Install Hibernate Tools ___________________________________________________________ 436 Hibernate Console Configuration ___________________________________________________ 437 Hibernate Console Perspective _____________________________________________________ 438 Hibernate Configuration View _____________________________________________________ 439 Class Diagram __________________________________________________________________ 440 HQL Editor ____________________________________________________________________ 441 Query Results __________________________________________________________________ 442 Properties View _________________________________________________________________ 443 SQL Preview ___________________________________________________________________ 444 Other Capabilities _______________________________________________________________ 445

Recap and Resources ______________________________________________________ 446 Recap_________________________________________________________________________ 447 What's Next ____________________________________________________________________ 448 Some Useful Resources___________________________________________________________ 449

20101220 Copyright © 2005-10, LearningPatterns Inc. All rights reserved viii

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 120101220

Fast Track to Hibernate

Fast Track to Hibernate 3

The Java Developer Education Series

LearningPatterns Inc.

Preface

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 220101220

Fast Track to Hibernate

Workshop Overview and Objectives

This is an in-depth course covering the use of Hibernate to access data in relational databases using JavaAt completion you should be able to write, deploy, and test Hibernate applications, and you will:– Understand the architecture of Hibernate– Be able to create applications that use Hibernate to map

persistent Java objects to a relational database– Use Hibernate versioning and optimistic locking– Map collections and associations using Hibernate– Model inheritance with Hibernate– Create and execute Hibernate queries– Be familiar with Hibernate annotations, and know the relationship

between Hibernate and the Java Persistence API– Be familiar with Hibernate design principals

Preface

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 320101220

Fast Track to Hibernate

Workshop Agenda

Session 1: Introduction to Hibernate

Session 2: Updates and Queries

Session 3: Lifecycle

Session 4: Relationships

Session 5: Additional Querying Capabilities

Session 6: Hibernate and Java Persistence API / EJB3

Session 7: Additional Topics

Preface

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 420101220

Fast Track to Hibernate

Release Level

This course contains instructions for running the Hibernate labs using the following platforms– Hibernate 3.6 (should work with 3.5 with little difference, and

with 3.3 with minor differences *)– Derby Database (Open Source DB from Apache)– Java 5+ – Eclipse Java EE Edition (Should work with most recent Eclipse

versions)

All labs have been tested on Windows XP

Instructions are based on the Windows operating system– If you are using Unix, you will need to adjust accordingly

If you are using Hibernate 3.5, the only difference from Hibernate 3.6 might be in the labs regarding the slf4j / log4j implementation jar

– This is given to you in the workspace\common\lib directory, and for 3.6, is named slf4j-log4j12-1.6.1.jar

– For Hibernate 3.5, you might need to get a different version of this jar file

For Hibernate versions earlier than 3.5, the labs should still work (though you'll might still need the proper slf4j-log4j jar)

– There might be some differences in the jar files that you need– If you get NoClassDefFound exceptions, you'll need to work

to fix that

Preface

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 520101220

Fast Track to 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 HttpServlet

– Filenames will be in italics, such as SearchServlet.java– We sometimes denote more info in the notes with a star *– Lastly, longer code examples will appear in a separate code box

as shown belowpackage com.javatunes.teach;public class JavaInstructor implements Teacher {

public void teach() {System.out.println("Hibernate is way cool");

}}

Preface

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 620101220

Fast Track to Hibernate

Labs

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

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

detailed instructions on what needs to be doneThe course includes setup zip files that contain skeleton code for the labs– Students just need to add code for the particular capabilities that

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

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

like this one to the right

Lab

STOP

Preface

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 720101220

Fast Track to Hibernate

Session 1: Introduction to Hibernate

Hibernate OverviewUsing Hibernate

Mapping a Simple ClassLogging

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 820101220

Fast Track to 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 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 920101220

Fast Track to Hibernate

Hibernate Overview

Hibernate OverviewUsing Hibernate

Mapping a Simple ClassLogging

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 1020101220

Fast Track to Hibernate

The Issues with Persistence Layers

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

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

incomplete– Changes to the database schema are often expensive to

propagate to the persistence layer

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

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

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

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 1120101220

Fast Track to Hibernate

Object-Relational Mapping (ORM) Issues

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

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

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

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

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

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

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 1220101220

Fast Track to 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 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 1320101220

Fast Track to Hibernate

Hibernate Overview

Open Source, ORM framework for Java

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

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

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

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

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

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 1420101220

Fast Track to Hibernate

Hibernate Benefits

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

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

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 1520101220

Fast Track to Hibernate

Hibernate Environments

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

using it in a Java SE and Java EE environment

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

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

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

migration path to standard Java Persistence

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 1620101220

Fast Track to 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 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 1720101220

Fast Track to Hibernate

More Detailed Architecture

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 1820101220

Fast Track to Hibernate

More Detailed Architecture

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

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 1920101220

Fast Track to Hibernate

Using Hibernate

Hibernate OverviewUsing Hibernate

Mapping a Simple ClassLogging

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 2020101220

Fast Track to 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 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 2120101220

Fast Track to 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 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 2220101220

Fast Track to Hibernate

Configuring Hibernate

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

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

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

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

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

– Programmatically via a Java API

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

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

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

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 2320101220

Fast Track to 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 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 2420101220

Fast Track to 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 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 2520101220

Fast Track to Hibernate

SessionFactory Configuration

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

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

Hibernate's behavior for a specific database

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 2620101220

Fast Track to Hibernate

SessionFactory Configuration Properties

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

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

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

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

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

For example there are properties forJDBC Tuning

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

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

hibernate.cache.use_second_level_cache, and moreHibernate Transaction Properties

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

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 2720101220

Fast Track to Hibernate

Example Properties for PostgresSQL

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

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

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

org.postgresql.Driver</property>

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

org.hibernate.dialect.PostgreSQLDialect</property>

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

</session-factory>

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

datasource JNDI name (hibernate.connection.datasource)

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

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

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

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

– [Hibernate 3.2.2 Reference Documentation, Section 1.2.3]

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 2820101220

Fast Track to Hibernate

The Configuration Class

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

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

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

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

– buildSessionFactory() creating a SessionFactory

– You can also configure Hibernate programmatically with a Configuration instance

– See the javadoc!

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

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

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

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

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

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

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 2920101220

Fast Track to 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 SessionFactoryconvenient

– We'll look at this later

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 3020101220

Fast Track to Hibernate

SessionFactory API

Here are some common methods of SessionFactory

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

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

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

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

– Many more methods – see the documentation

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

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

– Get metadata about entities managed by the factory

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 3120101220

Fast Track to Hibernate

The Session Interface

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

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

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

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

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

– Long transactions might span several database transactions.

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 3220101220

Fast Track to 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 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 3320101220

Fast Track to Hibernate

A Basic Hibernate Program Example

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

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

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

SessionFactory sf;Session s;

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

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

}

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

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

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

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 3420101220

Fast Track to Hibernate

Lab 1.1 – Setting up Hibernate

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 3520101220

Fast Track to Hibernate

A Hibernate Application

Overview: In this lab you will become familiar with and set up your environment, and create a simple Hibernate application– The environment consists of the open source Derby database,

and the Eclipse Development environment

Objectives:– Set up a database (the open source Derby database)– Create an Eclipse project that has all the needed libraries

(Hibernate and JDBC driver)– Configure hibernate and write a simple hibernate application

Builds on previous labs: None

Approximate Time: 30-40 minutes

Lab

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 3620101220

Fast Track to Hibernate

Information Content and Task Content

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

Tasks that the student needs to perform are in a box with a slightly different look – to help you identify themAn example appears below

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

OK – we're ready to start working

Lab

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 3720101220

Fast Track to Hibernate

Setup the Environment Lab

Tasks to PerformMake sure that you have Java 5 or 6 installed– Java 5 standard installation directory is

C:\Program Files\Java\jdk1.5.0_nn– Java 6 standard installation directory is

C:\Program Files\Java\jdk1.6.0_nnMake sure that you have Eclipse installed– Standard location is in c:\eclipse– If not installed, downloadable from

http://www.eclipse.org/downloads/Make sure that you have Hibernate 3.6 * installed– Likely in a directory like c:\hibernate-distribution-3.6.0.Final– If not installed, downloadable from http://www.hibernate.org

To download Eclipse, download the zip file for it, and unzip it to C:\– That's all that's needed for installation, though you can copy a shortcut from

C:\eclipse\eclipse.exe to your desktop to make starting Eclipse easier

The instructions in the labs assume Hibernate 3.6, and Eclipse 3.6– If you use a different platform, you'll need to modify the lab instructions somewhat– Most recent versions of either should work

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 3820101220

Fast Track to Hibernate

Extract the Lab Setup Zip File

To set up the labs, you'll need the lab setup file * – The file name is something like: Hibernate_LabSetup_20101220.zip

Our base working directory for this course will be C:\StudentWork\HibernateThe C:\StudentWork\Hibernate\Derby directory contains database files and various command scripts we will use– All instructions assume that this zip file is extracted to C:\. If you

choose a different directory, please adjust accordingly

Lab

Tasks to PerformUnzip the lab setup file to C:\– This will create the directory structure,

shown on the next slide, containing files you'll need for doing the labs

The setup zip will either be given to you on a CD, be present onyour machines or supplied by your instructor

If you have a CD, it may also contain additional folders with extra content

– InstallFiles: Extra software install files (e.g. simple editor)– Resources: Documentation, specifications, etc.– Which extra files are supplied will vary based on space

limitations

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 3920101220

Fast Track to Hibernate

Lab Directory Structure

StudentWork\Hibernate contains– Derby: Database files– Resources : Extra files (e.g. docs)– Setup: files needed for lab work

• LabNN: directory for any lab with additional setup files

– workspace: Lab directories

StudentWork\Hibernate\workspacewill contain the following folders:– common: shared files– LabNN : Directory for Lab NN– LabNN/bin/ : compiled code (we use

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

Lab

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

– Go to the StudentWork\Hibernate\Utilities\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 Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 4020101220

Fast Track to Hibernate

Start the Database

We are using the open source Derby database for the labs– We will set up and run this database using a number of scripts supplied

in the setup in C:\StudentWork\Hibernate\Derby

Lab

Tasks to PerformOpen the StudentWork\Hibernate\Derby\dbSetenv.cmd file– Look at how DB_NAME is set (you don't need to change this):set DB_NAME=jdbc:derby://localhost:1527/JavaTunesDB

– This sets the server that our tools will talk to• The server on localhost listening on the standard Derby server port• Using the database with the name JavaTunesDB

Start the Derby database server– Execute dbStart.cmd (you can double-click on it)– This starts a standalone Derby server that can accept network

connections to the database

Derby is an open source all-Java database environment that was originally developed as the Cloudscape database

– It was contributed by IBM to the Apache Software Foundation

– See http://db.apache.org/derby/– Provides developers with a database for use in developing

enterprise applications, using J2EE technologies

You shouldn't need to change anything in dbSetenv.cmd– We have you look at it so you understand how the scripts are

set up

If you have trouble running the scripts, try opening a command window in the Derby folder, and then running them

– This way the window stays around long enough to read the error messages

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 4120101220

Fast Track to Hibernate

Creating and Browsing the Database Lab

ij> select * from item;... Lots of output ...

ij> exit;

Tasks to PerformCreate the database– Execute dbCreate.cmd (you can double-click on it)

• This creates the JavaTunesDB database• You can ignore a DROP TABLE error, if you see it

Execute dbSQL.cmd to run ij (you can double-click on it)– This command file is set up to connect to the correct database– Using ij, browse the DB to check the setup (sample SQL below)

ij is Derby's SQL command line tool– It allows us to create database objects and view and manipulate

database data, without having to write code to do so– Most database packages provide such a tool

dbCreate.cmd generates a DROP TABLE error the first time it is run, because it drops the Item table, which doesn't exist the first time, then creates it.

– The database for this course consists only of the Item table.– If you ever want a "fresh" database, simply rerun dbCreate.cmd.

dbSQL.cmd launches the ij program , a command line SQL tool.– All commands in ij are terminated with a semicolon (;). For help, type help;. To exit,

type exit;.

To stop the database server, run the dbStop.cmd program– But leave it running for now

Some classrooms use a single central database serverIn this case, each student should append a unique number to the name of the database

– e.g. JavaTunesDB1 for the 1st student, JavaTunesDB2 for the 2nd, etc.– This will give each student their own database to work with

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 4220101220

Fast Track to Hibernate

General Instructions

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

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

– In general, all the files you will work on for a lab will be under the root directory (and instructions are given relative to this directory)

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

environment, as well as details about the lab requirementsSubsequent labs require you to do the same thing as this lab to build/run, so they don't include detailed instructions on howto do so

Lab

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 4320101220

Fast Track to Hibernate

The Eclipse Development Environment

We will use Eclipse, an open source platform for building IDEs, for programming our labs– Used mainly for Java development– Can be extended via plugins to create applications useful in

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

The remainder of this lab includes 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 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 Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 4420101220

Fast Track to Hibernate

Launch Eclipse Lab

Tasks to PerformLaunch Eclipse if you haven’t already– Go to c:\eclipse and run eclipse.exe– A dialog box should appear prompting for a workbench location– Set the workbench location to C:\StudentWork\Hibernate\workspace– If a different default Workbench location is set, change it

If you've already opened to another workspace, you can go to File -> Switch Workspace … to open the correct one

You can put a shortcut to eclipse.exe on your desktop for convenience

If Eclipse was installed elsewhere, then adjust the above directions accordingly

If Eclipse was not installed, the setup zip file is available on the CD under the InstallFiles folder

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 4520101220

Fast Track to Hibernate

Workbench and Java Perspective

Tasks to PerformClose the Welcome screen (click the X on its tab – see notes)You should be in a Java EE perspective - depending on which Eclipse version you use– If in a Java perspective, that's fine - there is nothing else to do

If in a Java EE perspective, open a Java one by clicking the Perspective icon at the top right of the Workbench, and select Java (as shown below left)Close the Java EE perspective by right clicking its icon, and selecting close (as shown below right)

Lab

To close welcome screen, click the X in the tab in the upper left corner, as shown at bottomThe Eclipse Java EE version opens in the Java EE perspective by default

– The Basic version, opens in the Java perspective, and you won't need to switch if using it

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 4620101220

Fast Track to Hibernate

Unclutter the Workbench

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

Lab

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

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

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 4720101220

Fast Track to Hibernate

Create User Libraries

We need to include many Hibernate jars in our classpath– We'll set these up as a user library, to make it easy to set up the

classpath each time we create a new project

Tasks to PerformGo to Window | Preferences | Java | Build Path | User Libraries– Click New…– In the next dialog, call the library Hibernate, and press OK– Click the Add JARs… button, browse to <hibernate> *, select

hibernate3.jar and select Open*You will need to add in all the jars listed on the following page– Each time you want to add jars, you'll need to select the

Hibernate library in the User Libraries dialog, click the Add JARs… button, browse to the appropriate directory, select the jars needed and click OK

Lab

<hibernate> stands for the directory that Hibernate is installed in– For example, C:\hibernate-distribution-3.3.0.SP1

hibernate3.jar contains the complete Hibernate distribution, and you need to include that on your classpathThe other jars in the lib directory are libraries that Hibernate depends on

– We don't really need all of them, but in this situation, it's the easiest way to add them

You can select multiple files in the dialog by using holding down the Control key as you select each file

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 4820101220

Fast Track to Hibernate

Create User Libraries

Tasks to PerformSelect the Hibernate library again, click Add JARs… and browse to <hibernate>\lib\required– Select all the files in this directory *– Click Open to add in all the selected jars

Similarly, browse to <hibernate>\lib\jpa and add in all the jars in that directory (JPA classes are used internally in Hibernate)Similarly, browse to C:\StudentWork\workspace\common\lib and add in all the jars in that directory (we'll explain these later)

Similarly, add in derbyclient.jar in the directory: C:\StudentWork\Hibernate\Derby\lib

Click OK to finish creating the library

Lab

You can type Ctrl-a (Hold down the Control and "a" key at the same time) in the file selector window to select all the filesFor Hibernate 3.2, add in the Hibernate jars as follows:

– Browse to <hibernate>\lib– Type Ctrl-a to select all the jars in the lib directory– Still holding down the Ctrl key, click xerces-2.6.2.jar to deselect it (not needed for JDK

1.4+)– Click Open to add in all the selected jars– You don't need to add in the jars in workspace\common\lib

derbyclient.jar is needed to run the database access labs that use the Derby database

If you haven't installed the student files in the standard C:\ location, then adjust any paths appropriately

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 4920101220

Fast Track to Hibernate

Create a Project for our Application

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

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

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

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

you can set the Java Settings for the project

Lab

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

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

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

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

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 5020101220

Fast Track to Hibernate

Add the Hibernate Library to ClassPath

Tasks to PerformIn the Java Settings dialog, click the Libraries tab *– Click the Add Library button, and in the dialog that comes up,

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

Lab

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

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

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

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

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

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 5120101220

Fast Track to Hibernate

Finish hibernate.cfg.xml

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

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

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

Lab

We include a few additional properties in the supplied configuration file

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

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 5220101220

Fast Track to Hibernate

Create a TestClass

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

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

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

the Java build path for the Hibernate project in Eclipse

Lab

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

• These are libraries that Hibernate uses

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 5320101220

Fast Track to 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 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 5420101220

Fast Track to Hibernate

Running Your Application

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

pane, right click on the TestHibernate.java file

– Select:Run As -> Java Application

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

Lab

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 5520101220

Fast Track to Hibernate

Testing your Application

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

Lab

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 5620101220

Fast Track to Hibernate

Debugging Problems

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

Lab

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

run configurations you've recently used

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 5720101220

Fast Track to 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 Hibernate library to the project build path to compile and run

Anytime you COPY files into a project (e.g. from setup) you need to Refresh it (Right click on the project, select Refresh)

For anyone not familiar with Eclipse, the next few slides give a(very) brief overview of how Eclipse is structured– There is nothing you need to do in those slides –

they are for information purposes only

Eclipse

Take note of the Lab instructions

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

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

– You'll do it in the same way as you created this one– There will be some instructions, and you can also come back

to this labAny lab that has you copy files from the setup to your working directory will require you to refresh the project as described above

– This allows Eclipse to become aware of the new files.

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 5820101220

Fast Track to 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

Eclipse

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

It is even possible to set up multiple workspaces (with corresponding Workbenchs). Simply create a folder to house the additional workspace, and write a script that uses the Eclipse executable file and supplies the ‘data’ argument with the location of the workspace directory to load:

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

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

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

plugins you have installed

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 5920101220

Fast Track to Hibernate

Workbench and Workspace

Workspace (Model)

Workbench (View)

Eclipse

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 Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 6020101220

Fast Track to Hibernate

Navigator View

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

• Correspond to files on the file system

– Folders• Like directories on the file system

– Projects• Used to organize all your resources and for version control.• When you create a new project, you assign a physical location for it on the file system.• A third-party SCM (Source Control Manager) may be used to properly share project files amongst developers.

Eclipse

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 Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 6120101220

Fast Track to Hibernate

Package Explorer

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

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

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

resources – for example to create a new class, just click on the package you want and select New | Class *

Eclipse

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 6220101220

Fast Track to Hibernate

Editors

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

STOP

Eclipse

Lab 1.1: Setting up Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 6320101220

Fast Track to Hibernate

Mapping a Simple Class

Hibernate OverviewUsing Hibernate

Mapping a Simple ClassLogging

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 6420101220

Fast Track to Hibernate

Persistent Entity Classes

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

Hibernate

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

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

defaults

Hibernate supports annotations that are compatible with the JavaPersistence API

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

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

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

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 6520101220

Fast Track to 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 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 6620101220

Fast Track to Hibernate

An Example Persistent Class

package com.javatunes;

import java.util.Date;

public class Event {

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

Event() {}

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

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

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

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

}

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 6720101220

Fast Track to Hibernate

The Event Class

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

properties– The class also has no-argument constructor

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

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 6820101220

Fast Track to Hibernate

The id Property

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

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

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

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

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

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

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

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

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

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

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 6920101220

Fast Track to Hibernate

The Hibernate Mapping File

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

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

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

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

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

<hibernate-mapping>

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

</class>

</hibernate-mapping>

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

[Hibernate Reference Documentation]

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 7020101220

Fast Track to 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 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 7120101220

Fast Track to Hibernate

The <class> Element

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

the class

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

in queries, other mappings

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

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

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

<!-- Property Mappings … -->

</class>

</hibernate-mapping>

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 7220101220

Fast Track to 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 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 7320101220

Fast Track to Hibernate

Mapping the id Property with <id>

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

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

primary key value for us

<hibernate-mapping>

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

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

</class>

</hibernate-mapping>

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

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 7420101220

Fast Track to Hibernate

More About Primary Keys

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

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

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

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

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

Session 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 7520101220

Fast Track to 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 1: Introduction to Hibernate

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 39920101220

Fast Track to Hibernate

Lesson Summary

JPA standardizes ORM and supports most of the capabilities that Hibernate supports– It also integrates with Java EE very cleanly

If you know Hibernate, it's not a bit jump to use JPA– The main difference is the use of annotations, rather than XML

mapping files– You can still use XML mapping files – JPA has their own

specification for this also, though we didn't cover it– In general, the annotation based mapping is more generally used

with JPA – it's simpler and seems to be easier for developers– The exception is with certain things where it is still useful to

externalize them to an XML file – for instance named queriesAll in all, the standardization of Java ORM should give a big push to its use

Session 6: Hibernate and the JPA

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 40020101220

Fast Track to Hibernate

Session 7: Additional Topics

Components and Multi-Table Mappingequals() and hashCode()

CachingDesign Considerations

Hibernate ToolsetResources

Session 7: Additional Topics

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 40120101220

Fast Track to Hibernate

Lesson Objectives

Explore several advanced topics in Hibernate, including:

– Embedded components– Multi-table mappings– Issues around the equals() and hashCode methods– Caching, including using a second-level cache– Design Considerations– Using the Hibernate Toolset

Session 7: Additional Topics

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 40220101220

Fast Track to Hibernate

Components and Multi-Table Mapping

Components and Multi-Table Mappingequals() and hashCode()

CachingDesign Considerations

Hibernate ToolsetResources

Session 7: Additional Topics

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 40320101220

Fast Track to Hibernate

Component Overview

Entities sometimes have data that can best be modeled by another type– For example, an Employee might have address information

(street, city, state, zip) that can be contained in an Addressobject

– It may also be the case that these types are not suitable to be entities – they aren't shared, and their lifetime is dependent on the containing event

– Hibernate lets you model this information as components

Components are contained objects that are persisted as value types, and owned by a parent entity– For example, an Address which is contained inside an Employee instance

Session 7: Additional Topics

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 40420101220

Fast Track to Hibernate

Component Example

Consider an EMPLOYEE table with the structure shown below– It would be convenient to encapsulate the address information in

a separate class– We show possible class definitions for this below

Here an Address component is used in an Employee– It will get populated with the address information from the

EMPLOYEE table in the DB

EMPLOYEE

PK ID

STREETCITYSTATEZIPOther Data

public class Address {private String street;private String city;private String state;private String zipcode;// details not shown

}

public class Employee {private Address address;// details not shown

}

Session 7: Additional Topics

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 40520101220

Fast Track to Hibernate

Mapping a Component

<component> is used to designate an embedded component– The EMPLOYEE table still has all the columns of data– However, when an Employee instance is created, for example in

a query result, an Address instance is created to hold the address data, instead of that data being in an Employee instance

– Similarly, if you create a new Employee instance, when the Employee is persisted the address data is taken from its contained Address instance

<class name="com.javatunes.Employee" table="EMPLOYEE"><!-- Other detail omitted --><component name="address" class="com.javatunes.Address">

<property name="street"/><property name="city"/><property name="state"/><property name="zipcode column="ZIP"/>

</component></class>

Session 7: Additional Topics

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 40620101220

Fast Track to Hibernate

Multi-Table Mapping

In other situations, you might have an entity that contains datathat spans more than one table– You don't really want to define a DB schema this way, but

sometimes you have to deal with legacy schemas where you need to combine data from multiple tables into one class

– Below we show an example where we have a separate table holding employee address information

– The class definition of Employee is below

EMPLOYEE

PK ID

Other Data

EMP_ADDRESS

PK,FK

EMP_ID

STREETCITYSTATEZIP

public class Employee {private String street;private String city;private String state;private String zipcode;// details not shown

}

Session 7: Additional Topics

Notes:

Copyright © 2005-10 LearningPatterns Inc. All rights reserved. 40720101220

Fast Track to Hibernate

Multi Table Mapping

Here is the mapping file for the previous example– <join> indicates that we are joining another table to the main

entity table– <key> specifies the primary key in the EMP_ADDRESS table– The nested <property> elements specify Employee properties

whose data is in the EMP_ADDRESS table

<class name="Employee" table="EMPLOYEE"><!-- Much Detail Omitted -->

<join table="EMP_ADDRESS"><key column="EMP_ID"/><property name="street"/><property name="city"/><property name="state"/><property name="zipcode column="ZIP"/>

</join></class>

Session 7: Additional Topics