Object-Relational Mapping (ORM)

treeexcellentSoftware and s/w Development

Dec 13, 2013 (3 years and 8 months ago)

80 views

Object-Relational Mapping (ORM)
and
Hibernate
Problemarea
Problem

area
•When working with object-oriented systems, there’s a
mismatch between the object modeland the relational
database
database
•How do we map one to the other?
public class Student
{
privateStringname;
private

String

name;
private String address;
private Set<Course> courses;
private Set<Degree> degrees;
}
}
Java object with properties
and associations
Relational database
with tables and columns
Problemarea
Problem

area
•How to map associations between objects?
–References are directional, foreign keys not
Foreignkeyscan

trepresentmany
to
manyassociations

Foreign

keys

cant

represent

many
-
to
-
many

associations
Student
Degree
NN
public class Student
{
private Collection<Degree> degrees;
Java
...
DEGREE
degree_id
type
name
STUDENT
student_id
name
address
degreeid
Relational
database / SQL
degree
_
id
Technology
Technology
(
Domain model
)
Whltildtb?
Student
Course
()

Wh
y re
l
a
ti
ona
l

d
a
t
a
b
ases
?
–Flexible and robust approach to data
mana
g
ement
g
–De-facto standard in software development
Degree
•Why object-oriented models?
–Business logic can be implemented in
Java(opposedtostoredprocedures)
Java

(opposed

to

stored

procedures)
–Allows for use of design patterns and
concepts like polymorphism
Idditibilit

I
mproves co
d
e reuse an
d
ma
i
n
t
a
i
na
bilit
y

Demandformappinginteraction!
(Database)

Demand

for

mapping

interaction!
ApproachestoORM
Approaches

to

ORM
•Write SQL conversion methods by hand using JDBC
–Tedious and requires lots of code
Extremelyerror
prone

Extremely

error
-
prone
–Non-standard SQL ties the application to specific databases

Vulnerable to chan
g
es in the ob
j
ect model
gj
–Difficult to represent associations between objects
Student
Course
public void addStudent( Student student )
{
String sql = ”INSERT INTO student ( name, address ) VALUES ( ’” +
Degree
student.getName() + ”’, ’” + student.getAddress() + ”’ )”;
// Initiate a Connection, create a Statement, and execute the query
}
ApproachestoORM
Approaches

to

ORM
•Use Java serialization

write application state to a file
–Can only be accessed as a whole
Notpossibletoaccesssingleobjects

Not

possible

to

access

single

objects

Objectorienteddatabasesystems
Object

oriented

database

systems
–No complete query language implementation exists
–Lacks necessary features
Thepreferredsolution
The

preferred

solution
U
Objt
RltilMiSt
(Hibt)

U
se a
Obj
ec
t
-
R
e
l
a
ti
ona
l

M
app
i
ng
S
ys
t
em
(
eg.
Hib
erna
t
e
)
•Provides a simple API for storing and retrieving Java
objectsdirectlytoandfromthedatabase
objects

directly

to

and

from

the

database
•Non-intrusive:No need to follow specific rules or design
p
atterns
p
•Transparent: Your object model is unaware
Student
Course
Degree
ORM / Hibernate
Magic happens
here!
here!
(Domain model)(Relational database)
ORMandArchitecture
ORM

and

Architecture
Presentation Laye
r
•Middleware that
manages persistence
Pidbtti
Service/Business Layer
Domain
Model

P
rov
id
es an a
b
s
t
rac
ti
on
layer between the
domainmodelandthe
Persistence Layer
domain

model

and

the

database
ORM / Hibernate
(Database)
(Database)
Exampleapp:TheEventManager
Example

app:

The

EventManager
Java
objects
Hibernate
API
Hibernate
mappingfiles
Hibernate
configuration
mapping

files
file
Javaobjects
Java

objects
public class Event
{
{
private int id;
private String title;
private Date date;
private Set<Person> persons = new HashSet<Person>();
Identifier property
public Event() {
}
public int getId() {
No-argument
constructor
return id;
}
private void setId( int id ) {
this.id
=
id;
Follows the
JavaBeannaming
this.id

id;
}
public String getTitle() {
return title;
}
JavaBean

naming

conventions
}
public void setTitle( String title ) {
this.title = title;
}
// Getter and setter for date and persons
}
Exampleapp:TheEventManager
Example

app:

The

EventManager
Java
objects
Hibernate
API
Hibernate
mappingfiles
Hibernate
configuration
mapping

files
file
Hibernatemappingfiles
Hibernate

mapping

files
•Tells Hibernate which tables and columns to use to load
and store objects
<
!DOCTYPEhibernate
-
mappingPUBLIC
DTD
!DOCTYPE

hibernate
mapping

PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<classname=

nouioinf5750Event

table=

events

>
Cllt
<class

name=no
.
uio
.
inf5750
.
Event

table=events>
<id name="id” column=”event_id”>
<generator class="native"/>
</id>
Cl
ass e
l
emen
t
Identifier mapping & generation
<property name=”title” not-null=”true” unique=”true”/>
<property name=”date” type=”date” column=”event_date”/>
<set name=”
p
ersons” table=”event
p
ersons”>
Property mapping
p
_
p
<key column=”event_id”/>
<many-to-many column=”person_id”
class=”no.uio.inf5750.example.model.Person”/>
</set>
Unidirectional many-to-many
association mapping
</class>
</hibernate-mapping>
Filename: Event.hbm.xml
Propertymapping
Property

mapping
Thenamepropertyrefers
Titlemustbe
The

name

property

refers

to the get/set-methods
Title

must

be
not null and unique
...
<property name=”title” not-null=”true” unique=”true”/>
<t”dt”t”Dt”l”tdt”/>
<
proper
t
y name=
”d
a
t
e


t
ype=
”D
a
t
e

co
l
umn=

even
t
_
d
a
t
e
”/>
...
Property name used as
defaultifnocolumnisspecified
Types are Hibernate mapping types.
Hibernatewillguessifnotypeisspecified
default

if

no

column

is

specified
Hibernate

will

guess

if

no

type

is

specified
.
Associationmapping
Association

mapping
Thenamepropertyrefers
Many
to
manyassociations
The

name

property

refers

to the get/set-methods
Many
-
to
-
many

associations
require a link table
...
<set name=”persons” table=”event_persons”>
Column name
for ”this” side
ofassociation
<key column=”event_id”/>
<many-to-many column=”person_id”
class=

nouioinf5750examplemodelPerson

/>
of

association
Cl
class=no
.
uio
.
inf5750
.
example
.
model
.
Person/>
</set>
...
C
o
l
umn name
for ”other” side
of association
Reference to the
associated class
Hibernatemappingtypes
Hibernate

mapping

types
HibilllJSQL/db

Hib
ernate w
ill
trans
l
ate
J
ava types to
SQL

/

d
ata
b
ase types
for the properties of your mapped classes
Java typeHibernate typeSQL type
java.lang.StringstringVARCHAR
javautilDate
datetime
DATETIME
java
.
util
.
Date
date
,
time
DATE
,
TIME
java.lang.Integer, intintegerINT
java.lang.Classclassvarchar
java.io.SerializableserializableBLOB, BINARY
Exampleapp:TheEventManager
Example

app:

The

EventManager
Java
objects
Hibernate
API
Hibernate
mappingfiles
Hibernate
configuration
mapping

files
file
TheHibernateconfigurationfile
The

Hibernate

configuration

file
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<
hibernate
-
configuration
>
DTD
hibernate
configuration
<session-factory>
<property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
<propertyname=
"
hibernateconnectionurl
"
>jdbc:hsqldb:hsql://localhost</property>
JDBC connection
configuration
<property

name=hibernate
.
connection
.
url>jdbc:hsqldb:hsql://localhost</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"></property>
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
Specifies the SQL
variant to generate
<property name="hibernate.connection.pool_size">10</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
Size of conn pool
Automatic generation
<mapping resource=”Event.hbm.xml"/>
<mapping resource=”Person.hbm.xml”/>
</session-factory>
of database schema
Mapping files
</hibernate-configuration>
Filename:
hibernate.cfg.xml
Exampleapp:TheEventManager
Example

app:

The

EventManager
Java
objects
Hibernate
API
Hibernate
mappingfiles
Hibernate
configuration
mapping

files
file
TheConfigurationclass
The

Configuration

class
•Represents a set of
mapping files
Mifilbifid
Configuration configuration = new Configuration()
.addResource( ”Event.hbm.xml” )
ddR(”Phbl”)

M
app
i
ng
fil
es can
b
e spec
ifi
e
d
programmatically or through
theHibernateconfigurationfile
.a
ddR
esource
(

”P
erson.
hb
m.xm
l”

)
;
the

Hibernate

configuration

file
•Intended as a startup-time
objec
t
Configurationconfiguration=newConfiguration();
...or...
objec
Configuration

configuration

=

new

Configuration();
configuration.configure();
LoadsHibernate.cfg.xml
Loads

Hibernate.cfg.xml
from the classpath
TheSessionFactoryinterface
The

SessionFactory

interface
•Obtained from a Configuration
instance
Shdliti
SessionFactory sessionFactory =
configuration.buildSessionFactory();

Sh
are
d
among app
li
ca
ti
on
threads

Mainpurposeistoprovide

Main

purpose

is

to

provide
Sessioninstances

Allowedtoinstantiatemore

Allowed

to

instantiate

more
than one SessionFactory

Sophisticatedimplementation
Sophisticated

implementation
of the factory design pattern
TheSessioninterface
The

Session

interface
•Obtained from a
SessionFactory instance
Mitiitfbt
Session session =
sessionFactory.openSession();

M
a
i
n run
ti
me
i
n
t
er
f
ace
b
e
t
ween
a Java application and Hibernate

Responsibleforstoringand

Responsible

for

storing

and

retrieving objects

Thinkofitasacollectionofloaded

Think

of

it

as

a

collection

of

loaded

objects related to a single unit of work
Instancestates
Instance

states

A
n object instance state is related to the
p
ersistence
context
Thittt
HibtSi
it

Th
e pers
i
s
t
ence con
t
ex
t
= a
Hib
erna
t
e
S
ess
i
on
i
ns
t
ance
•Three types of instance states:
Transient

Transient
•The instance is notassociated with any persistence context

Persistent
•The instance is associated with a persistence context
–Detached
Thititdithittthihh

Th
e
i
ns
t
ance was assoc
i
a
t
e
d
w
ith
a pers
i
s
t
ence con
t
ex
t
w
hi
c
h

h
as
been closed –currently notassociated
TheSessioninterface
The

Session

interface
Event event = new Event( ”title”, new Date() );
Itid(It)i
(t)
Make a transient object
persistent
I
n
t
eger
id
=
(I
n
t
eger
)
sess
i
on.save
(
even
t

)
;
Eventevent=(Event)session
load
(Eventclassid);
Load an object –if
Event

event

=

(Event)

session
.
load
(

Event
.
class
,
id

);
matching row exists
Load an object –if
unsure about matching row
Event event = (Event) session.get( Event.class, id );
Delete an object –make
it transient again
session.delete( event );
TheSessioninterface
The

Session

interface
session.update( event );
Update an object –if its
detached
session
saveOrupdate
(event);
Update or save an object –if
session
.
saveOrupdate
(

event

);
you’re unsure about the state
Synchronize database with
persistence context
session.flush(); // Happens auto. at transaction.commit()
TheCriteriainterface
The

Criteria

interface
•You need a querywhen you don’t know the identifiers of
the objects you are looking for
Citidf
ti
ti

C
r
it
er
i
a use
d

f
or
p
rogramma
ti
cquery crea
ti
on
Criteriacriteria=session
createCriteria
(Eventclass);
Criteria

criteria

=

session
.
createCriteria
(

Event
.
class

);
List events = criteria.list();
Retrieve all instances of Event
Criteria criteria = session.createCriteria( Event.class );
criteria.add( Restrictions.eq( ”title”, ”Rolling Stones” ) );;
criteria.add( Restrictions.gt( ”date”, new Date() ) );
criteria.setMaxResults( 10 );
List events = criteria.list
();
Narrow the result set
();
Transactions
Transactions
•Transaction: A set of database operations which must be
executed in entirety or not at all
Shlddithith
it
llbk

Sh
ou
ld
en
d
e
ith
er w
ith
a comm
it
or a ro
llb
ac
k
•All communication with a database has to occur inside a
transaction!
transaction!
Transaction begins
Operation A: INSERT INTO...
Transaction rollback
Operation B: INSERT INTO...
(SUCCESS)
(ERROR)
Transaction commit
Transactions
Transactions
•Most common pattern
is session-per-request
Session session = sessionFactory.openSession();
Transaction transaction = null;
(REQUEST)
Retrieve a Hibernate Session
try
{
transaction = session.beginTransaction();
session.save(event);
Begin new transaction
session.save(

event

);
session.save( person );
transaction.commit();
}
catch(RuntimeExceptionex)
Execute database operations
catch

(

RuntimeException

ex

)
{
if ( transaction != null )
{
transaction.rollback();
Commit transaction
FlushandcloseSession
throw ex;
}
}
finally
{
Flush

and

close

Session
(RESPONSE)
{
session.close();
}
Example:TheEventManager
Example:

The

EventManager
Java
objects
Hibernate
API
Hibernate
mappingfiles
Hibernate
configuration
mapping

files
file
AdvantagesofORM
Advantages

of

ORM
•Productivity
–Eliminates lots of repetitive code –focus on business logic
Databaseschemaisgeneratedautomatically

Database

schema

is

generated

automatically
•Maintainability

Fewerlinesofcode

easiertounderstand

Fewer

lines

of

code


easier

to

understand
–Easier to manage change in the object model
AdvantagesofORM
Advantages

of

ORM
•Performance
–Lazy loading –associations are fetched when needed
Caching

Caching
•Database vendor independence

Theunderlyingdatabaseisabstractedaway

The

underlying

database

is

abstracted

away
–Can be configured outside the application
Resources
Resources
•Books on Hibernate
–Christian Bauer and Gavin King: Hibernate in Action
JamesElliot:
Hibernate
ADeveloper

snotebook

James

Elliot:

Hibernate


A

Developers

notebook
–Justin Gehtland, Bruce A. Tate:Better, Faster, Lighter Java
•The Hibernate reference documentation

www.hibernate.org
www.hibernate.org