v 6, 2006-09-28 mats strandberg orm with hibernate

38
v 6, 2006-09-28 Mats Strandberg ORM With Hibernate

Upload: rebecca-barker

Post on 26-Mar-2015

228 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

ORM With Hibernate

Page 2: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Presentation

Impedance mismatchWhat is ORMWhen/why use ORMUnderstand Hibernate basicsSee Java using Hibernate APISee SQLUnderstand Hibernate featuresAsk questions

Page 3: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Crisp Utbildningsdag (Crisp RD)

Crisp RDEvery second Friday, usually by employeeSome presentations at KTH

Mats StrandbergWorked with several OODBs since 1990Used RDBs in several OO projectsUsed Hibernate in one commercial projectWorked with Java since 1996

Page 4: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Simple Domain Model

Event

Participant

Venue

Address

0..n

0..n

1

1

0..n

0..n

Page 5: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Simple Domain Model

Event

Participant

Venue

Address

0..n

0..n

1

1

name

street

cityname

name

0..n

0..ndate

Page 6: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Object Diagram

hibernateRd: Event

mats : Participant

theVenue : Venue

theAddress : Address

name=”rum 1537”

street=”Osquars Backe 2”

city=”Stockholm”name=”Mats Strandberg”

name=”Hibernate RD”

date=”20060929 9.00”

Page 7: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Example Code and Mapping File

Page 8: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Relational Schema

Events

Participants

VenuesAddresses

* VenueId* AddressId

street

* ParticipantId

* EventId

name

EventParticipations* ParticipantId

* EventIdname

date

EventVenuename

VenueAddresscity

Page 9: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Example execution

Page 10: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

On Root Objects

In an object graph usually there’s roots, where navigation starts.

Root

Page 11: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Navigation

event.getVenue().getAddress().getStreet();

Event

Participant

Venue

Address

name

street

cityname

name

date

SELECT street FROM Addresses WHERE AddressId=(SELECT VenueAddress FROM Venues WHERE VenueId=(SELECT EventVenue FROM Events WHERE EventId=1));

Page 12: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Query

List list = // get events

for (Iterator iter = list.iterator(); iter.hasNext(); ) {

Event event = (Event) iter.next();

Address address = event.getVenue().getAddress();

if ("Stockholm".equals(address.getCity())) {

System.out.println("'" + address.getStreet() + "' is in Stockholm");

}

}

Event

Participant

Venue

Address

name

street

cityname

name

date

Get streets in Stockholm

SELECT street FROM Addresses WHERE city="Stockholm";

Page 13: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Object Queries

Roots may not be enough for searchWe need at least class extension orOQL

Page 14: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

HQL

List list =

session.createQuery(

"select street from Address where city='Stockholm'").list();

for (Iterator iter = list.iterator(); iter.hasNext(); ) {

System.out.println("'" + iter.next() + "' is in Stockholm");

}

Event

Participant

Venue

Address

name

street

cityname

name

date

Get street in Stockholm

SELECT street FROM Addresses WHERE city="Stockholm";

Page 15: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Example: Hibernate + Domain model

Take a look at: JavaSQL

Page 16: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Why a Database?

Need for persitent stateSupport for transactionsLarge data setsMultiple concurrent applications share dataData distributionUsually disk based (persistence with single node)

Only add complexity to solve a real problem

Page 17: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Reasons for Object Persistence vs RDBReasons to use OODB or ORM:

Use of OO in design and programming(avoid impedance mismatch)Domain Model Intense solutionHierarchic dataNavigational access

Page 18: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Reasons For ORM vs OODB

Legacy RDB (Relational Database)(RDB) vendor independenceVendor stability(?)Schema migrationTools

Page 19: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Alternatives to ORM

Hand coded persistance layerSerializationEJB/CMPOODB

Page 20: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Hibernate

Open SourceLGPL Licencehttp://hibernate.org

Page 21: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Hibernate is ”non-intrusive”

This means:Persistence is orthogonal to classPersisting a instance is a run-time decision

Page 22: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Requirements for a Persistent Class

Hibernate is said to ”non-intrusive”, however:Classes must have a no-arg constructorClasses should have a private Long id;Classes may have private database attributes

Page 23: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Understand ORM to use it

”The effective use of ORM technology in all but the simplest of enterprise environments requires understanding and configuring how the mediation between relational data and

objects is performed”

Linda DeMichiel, Lead Architect EJB, Sun

Page 24: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Impedance Mismatch

Identity GranularityObject navigationSubtypesPolymorphic associations

Page 25: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Inheritance

Table per concrete class

Aa1

Bb1

Cc1

B

a1

C* id

a1

* id

A* id

a1

b1

b1 c1

c1

A* id

B* id

C* id

a1

b1 c1

Table per class

hierarchy

Table per class

Page 26: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Application Transactions

A.k.a. long running transactionsAn object graph can be detachedUpdates can be done while detachedThe object graph can later be attached to a session

session.close() detaches the objectssession.update(object) attaches the object

NOTE: Other updates may be clobbered!

Page 27: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Detached objects + automatic versioningHandle concurrent updates by versioning

A version attribute must be added to classes involvedDetach object by session.close() Updates can be done while detachedAttach with session.update(object) Exception thrown by Hibernate at flush (commit) if version mismatch

Page 28: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Lazy vs Eager fetch

Event Venue Address

name street

city

name

date

Venue$

name

isA

Page 29: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Consider Performance

Iterating over a Class (Event) that has a n to m association

List list =

session.createQuery("from Event").list();

for (Iterator i = list.iterator(); i.hasNext(); ) {

Event event = (Event) i.next();

out.println("EVENT name:" + event.getName());

}

Page 30: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Lazy initialization

A Proxy is usedGetters are overridden, e.g. Event.getName();

The Proxy is a subclass of your persistent class, e.g extends EventRequires build-time bytecode instrumentationBeware of explicit comparison of runtime class, passing of class objects etc.

Page 31: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

CachingFirst-level Cache

Session

Second-level Cache

Query CacheCache Concurrency Strategy

Cache Provider

Page 32: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Testing without database?

Testing business logic:Hibernate is non-intrusive -> Use POJOs in a transient wayThink of transaction demarcationBeware of embedding HQL as it requires a DB.

Page 33: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Hibernate Product Suite

Hibernate CoreHibernate AnnotationsHibernate EntityManager Hibernate ToolsNHibernateJBoss Seam

Page 34: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Roadmap

Production:Hibernate 3.1NHibernate 1.0 for :NET (Hibernate 2.1)

Development:Hibernate 3.2 (EJB 3.0)NHibernate 1.2 (.NET Framework 2.0)NHibernate 3.x? (Hibernate 3)

Page 35: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Entity Manager

Entity Manager implements a complete EJB3 persistence provider (together with Hibernate Annotations)EJB-QL based on HQLAutomatic VersioningDetached EntitiesNon-managed set-up is rather differentEJB3 has a large number of persistence contexts

Page 36: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Features

Two Level CacheLocking strategies (e.g. Optimistic Locking)Application TransactionsComposition InheritancePolymorphismPersistence by reachabilityFetching strategies: Lazy vs EagerLazy initialization

Page 37: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Books on Hibernate

Etc.

Page 38: V 6, 2006-09-28 Mats Strandberg ORM With Hibernate

v 6, 2006-09-28

Mats Strandberg

Things to Mention

LockingJPA – Java Persistence APIIndexHibernate vs Manual ORM: When using Hibernate there is a ”standard” for how the mapping has been done. This is good for maintenanceBidirectional relations are handled at code level