Hibernate An Introduction

43
Basic Fundamentals Conclusion Hibernate: An Introduction Cao Duc Nguyen [email protected] Software Designer HP Software Products and Solution May 3, 2012

description

This presentation gives an introduction about Hibernate which covers fundamental concepts such as POJOs, Data Model, Persistent Lifecycle, HQL, etc.

Transcript of Hibernate An Introduction

Page 1: Hibernate An Introduction

Basic Fundamentals Conclusion

Hibernate: An Introduction

Cao Duc [email protected]

Software DesignerHP Software Products and Solution

May 3, 2012

Page 2: Hibernate An Introduction

Basic Fundamentals Conclusion

Talk Outline

1 BasicGetting StartedProblemChallenges

2 FundamentalsConceptsData ModelPersistent LifecycleHQLArchitecture

3 Conclusion

Page 3: Hibernate An Introduction

Basic Fundamentals Conclusion

Getting Started

Setting up the Environment

JDKAnt/MavenMySQL/PostgreSQL/Oracle, etc.JDBCEclipse Hibernate Tools

Page 4: Hibernate An Introduction

Basic Fundamentals Conclusion

Getting Started

Hibernate ORM distribution

Page 5: Hibernate An Introduction

Basic Fundamentals Conclusion

Problem

Hibernate - Definitions

by Hibernate.orgHibernate is concerned with helping yourapplication to achieve persistence. . . Persistencesimply means that we would like our application’sdata to outlive the applications process. . . wouldlike the state of (some of) our objects to livebeyond the scope of the JVM so that the samestate is available later.

by Wikipedia.orgHibernate is an object-relational mapping (ORM)library for the Java language, . . . a framework formapping an object-oriented domain model to atraditional relational database . . .

Page 6: Hibernate An Introduction

Basic Fundamentals Conclusion

Problem

Traditional View

Page 7: Hibernate An Introduction

Basic Fundamentals Conclusion

Problem

Traditional View (cont.)

Page 8: Hibernate An Introduction

Basic Fundamentals Conclusion

Problem

Hibernate View

Page 9: Hibernate An Introduction

Basic Fundamentals Conclusion

Challenges

Two Different Worlds

Object-Oriented SystemsSystem composed of objects interacting with each otherObjects encapsulate data and behaviors

Relational DatabasesData is stored in tables composed of rows

Page 10: Hibernate An Introduction

Basic Fundamentals Conclusion

Challenges

Obstacles

IdentityGranularityAssociationsNavigationInheritance & PolymorphismData type mismatches

Page 11: Hibernate An Introduction

Basic Fundamentals Conclusion

Concepts

Plain Old Java Object (POJOs)

In general, a POJO is a Java object not bound by any restrictionother than those forced by the Java Language Specification.However, due to technical difficulties and other reasons, in thecontext of Hibernate, a POJO is defined as follow:

No-argument class constructorProperty accessor (get/set) methodsClass is not declared final nor has final methods.Collection-typed attributes must be declared as interfacetypes.

Page 12: Hibernate An Introduction

Basic Fundamentals Conclusion

Data Model

Example Application: EventApp

Event-management application used to manage a conferencewith speakers, attendees, and various locations, among otherthings.

Page 13: Hibernate An Introduction

Basic Fundamentals Conclusion

Data Model

An Example: EventApp

Page 14: Hibernate An Introduction

Basic Fundamentals Conclusion

Data Model

Identity Mapping

<id name="id" column="id" type="long"><generator class="native"/></id>

Mapped classes must declare the primary key column ofthe database table.Generators using the native class will use identity orsequence columns depending on available databasesupport. If neither method is supported, the nativegenerator falls back to a high/low generator method tocreate unique primary key values.The native generator returns a short, integer, or long value.Hibernate documentation about Identity mapping here.

Page 15: Hibernate An Introduction

Basic Fundamentals Conclusion

Data Model

Property Mapping

<property name="startDate" column="start_date"type="date"/>

A typical Hibernate Property mapping defines a POJOproperty name, a database column name, and the name ofa Hibernate type, and it is often possible to omit the type.Hibernate uses reflection to determine the Java type of theproperty.Details about Hibernate Types mapping here.Hibernate documentation about Property mapping here.

Page 16: Hibernate An Introduction

Basic Fundamentals Conclusion

Data Model

Entity Mapping

<class name="Event" table="events"><!-- define identity, properties, components,collections, associations here... --></class>

A typical Hibernate Entity mapping defines a POJO classname, a database table name.By default, all class names are automatically “imported”into the namespace of HQLHibernate documentation about Entity mapping here.

Page 17: Hibernate An Introduction

Basic Fundamentals Conclusion

Data Model

Component Mapping

<component name="componentName"class="componentClass">

<!-- defines properties of the component herethese properties will be mapped to columns ofthe enclosing entity--></class>

A Hibernate Component mapping is defined within anEntity mapping several objects into one single table of theenclosing entity.Hibernate documentation about Component mapping here.

Page 18: Hibernate An Introduction

Basic Fundamentals Conclusion

Data Model

Put it all together

Hibernate Mapping files:

The Event.hbm.xml mapping file

Page 19: Hibernate An Introduction

Basic Fundamentals Conclusion

Data Model

Put it all together (cont.)

The Location.hbm.xml mapping file

Page 20: Hibernate An Introduction

Basic Fundamentals Conclusion

Data Model

Put it all together (cont.)

Hibernate Configuration hibernate.cfg.xml file:

Page 21: Hibernate An Introduction

Basic Fundamentals Conclusion

Data Model

Collection Mapping

Common Collections: sets, lists, bags, maps of value types.Value Type:

An object of value type has no database identity; it belongsto an entity instance, and its persistent state is embeddedin the table row of the owning entityValue-typed classes do not have identifiers or identifierproperties

Page 22: Hibernate An Introduction

Basic Fundamentals Conclusion

Data Model

Collection Mapping (cont.)

Hibernate persistent collections

Page 23: Hibernate An Introduction

Basic Fundamentals Conclusion

Data Model

Collection Mapping (cont.)

Example of persisting collections

Page 24: Hibernate An Introduction

Basic Fundamentals Conclusion

Data Model

Inheritance Mapping

Table per concrete class with union:

Page 25: Hibernate An Introduction

Basic Fundamentals Conclusion

Data Model

Inheritance Mapping (cont.)

Table per class hierarchy:

Page 26: Hibernate An Introduction

Basic Fundamentals Conclusion

Data Model

Inheritance Mapping (cont.)

Table per subclass:

Page 27: Hibernate An Introduction

Basic Fundamentals Conclusion

Persistent Lifecycle

Object States

TransientThe object is not associated with any persistencecontext. It has no persistent identity (primary keyvalue).

PersistentThe object is currently associated with apersistence context. It has a persistent identity(primary key value) and, perhaps, a correspondingrow in the database. Hibernate guarantees thatpersistent identity is equivalent to Java identity.

Page 28: Hibernate An Introduction

Basic Fundamentals Conclusion

Persistent Lifecycle

Object States (cont.)

DetachedThe instance was once associated with apersistence context, but that context was closed,or the instance was serialized to another process.It has a persistent identity and, perhaps, acorrsponding row in the database. For detachedinstances, Hibernate makes no guarantees aboutthe relationship between persistent identity andJava identity

Page 29: Hibernate An Introduction

Basic Fundamentals Conclusion

Persistent Lifecycle

State Transition Diagram

Page 30: Hibernate An Introduction

Basic Fundamentals Conclusion

Persistent Lifecycle

Case 1: Making an object persistent

Item item = new Item();item.setName("Playstation3 incl. all accessories");item.setEndDate( ... );Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();Serializable itemId = session.save(item);tx.commit();session.close();

Page 31: Hibernate An Introduction

Basic Fundamentals Conclusion

Persistent Lifecycle

Case 2: Retrieving a persistent object

Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();Item item = (Item) session.load(Item.class,new Long(1234));// Item item = (Item) session.get(Item.class,// new Long(1234));tx.commit();session.close();

Page 32: Hibernate An Introduction

Basic Fundamentals Conclusion

Persistent Lifecycle

Case 3: Modifying a persistent object

Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();Item item = (Item) session.get(Item.class,new Long(1234));item.setDescription("This Playstation isas good as new!");tx.commit();session.close();

Page 33: Hibernate An Introduction

Basic Fundamentals Conclusion

Persistent Lifecycle

Case 4: Making a persistent object transient

Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();Item item = (Item) session.load(Item.class,new Long(1234));session.delete(item);tx.commit();session.close();

Page 34: Hibernate An Introduction

Basic Fundamentals Conclusion

Persistent Lifecycle

Case 5: Reattaching a modified detached instance

// Loaded in previous Sessionitem.setDescription(...);Session sessionTwo = sessionFactory.openSession();Transaction tx = sessionTwo.beginTransaction();sessionTwo.update(item);item.setEndDate(...);tx.commit();sessionTwo.close();

Page 35: Hibernate An Introduction

Basic Fundamentals Conclusion

HQL

Query

HQL Query:

HQL SQLQuery:

Page 36: Hibernate An Introduction

Basic Fundamentals Conclusion

HQL

Parameter Binding

Page 37: Hibernate An Introduction

Basic Fundamentals Conclusion

HQL

Joins

Join:

Left Join:

Page 38: Hibernate An Introduction

Basic Fundamentals Conclusion

HQL

Criteria API

Some developers prefer to build queries dynamically, using anobject-oriented API, rather than building query strings.Hibernate provides an intuitive org.hibernate.Criteriarepresents a query against a particular persistent class:

Page 39: Hibernate An Introduction

Basic Fundamentals Conclusion

HQL

DetachedCriteria

A DetachedCriteria is used to express a subquery.

Page 40: Hibernate An Introduction

Basic Fundamentals Conclusion

Architecture

Structural Components

More in depth explanation can be found here.

Page 41: Hibernate An Introduction

Basic Fundamentals Conclusion

Architecture

Hibernate Flexibility and Extendibility

Extension points:Dialects (for different databases)Custom mapping typesID generatorsCache, CacheProviderTransaction, TransactionFactoryPropertyAccessorProxyFactoryConnectionProvider

Page 42: Hibernate An Introduction

Basic Fundamentals Conclusion

Why Hibernate?

Free, open source Java packageRelease developers from data persistent related tasks,help to focus on objects and features of applicationNo need for JDBC API for Result handlingDatabase almost-independenceEfficient queries

Page 43: Hibernate An Introduction

Basic Fundamentals Conclusion

THANK YOU *-*