hibernate 68

68
OR Mapping with Hibernate

Upload: smita-r-s

Post on 03-Apr-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 1/68

OR Mapping with Hibernate

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 2/68

Persistence in OO Apps

• In an object oriented application, persistence allows an

object to outlive the process that created it.

• The state of an object can be stored to a disc, and an

object with the same state can be re-created at somepoint in future.

• Persistence Technologies:

• JDBC

• JDO

• iBATIS

• TopLink

• EJB 2.1 Entity Beans

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 3/68

Why ORM?

• We want to work with

objects having behavior,

not rows and columns of 

data.

• Object-relational

paradigm mismatch.

Presentation Tier 

Persistence Tier 

Business Tier 

DB

Java

Developers

DBAs

Object-relational

 paradigm mismatch

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 4/68

Paradigm Mismatch

• The problem of Subtypes

• Problems related to Associations

• The problem of Identity

• The problem of Granularity

• Example- MegaMusic- an imaginary entertainment

businessArtist

id 

firstName

lastName

description

concerts

artist

Concert

id 

title

date

venue

artists

concert

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 5/68

The problem of subtypes

• Java supports type inheritance. A table in

SQL DB is not a type.

•  SQL DB products don’t support type of table

inheritance.

• No polymorphic association.

• So how does ORM help?

• Inheritance Mapping

Table per class hierarchy

Table per subclass

Table per concrete class

• Also, with Hibernate, you can fire

polymorphic queries 

Artistid 

firstName

lastName

description

concerts

Rock Artist

 wishList

genre

guitarType

drumType

 preferences

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 6/68

Association problems

• OOPL represents associations using object references (HAS-A relationship).

• In the relation world, associations are represented as foreign keys.

• Java relationships can be many-to-many. To represent many-to-manyrelationships btw two relations we need a join table which doesn’t appearanywhere in the domain model.

Artist

id 

firstName

lastName

description

concerts

artist

Concert

id 

title

date

venue

artists

concert

Artist_Concert

concert

artist_id

concert_id

artist

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 7/68

The problem of Identity

• Identity of Java objects can be

expressed as:

• Object Identity (checked with

==)

• Object Equality (booleanequals(Object))

• The identity of a DB row is

expressed as the primary key

value.

• Two objects which are

different in JVM heap can

represent the same DB row.

DBJVM Heap

artistartist

artistartist

artistartist

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 8/68

The problem of Granularity

• Granularity refers to the size of 

the type you’re working with. 

• The domain model offers three

levels of granularity:• Concert

• Venue

• String

• Whereas, the relational DBs

offer just two levels (next

slide).

Concert

id 

title

date

artists

venue

concert

Venue

country

zip

street

state

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 9/68

Granularity (contd.)

• The relational DBsoffer just two levels:

• Table such asConcert and,

• Columns such ascountry, state ..

• What does ORMapping Provide?

AssociationMappings 

Concert

id 

title

date

artists

venue

concert

Concert

id 

title

date

artists

countryconcert

state

zip

streetVenue

country

zip

street

state

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 10/68

Persistence Implementation

• There are various ways the persistence layer can be

implemented:

Hard-coding with SQL/JDBC

(more development and maintenance efforts are required) XML Persistence

(just another text file; no capabilities for DB mgt. )

Using Object Serialization

Other ORM Solutions

(iBATIS, JDO, TopLink, JPA)

EJB 2.1 Entity Beans.

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 11/68

Problems with Object

Serialization

• A serialized network of interconnected objects can only

be accessed as a whole; it’s impossible to retrieve any

data from the stream without desterilizing the whole

stream.• It’s impossible to access or update a single object or a

subset of objects independently.

• Loading and overwriting an entire network of objects

causes hits performance.

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 12/68

Hibernate vs. Entity Beans

EJB 2.1 Programming Model

<<Home Interface>>ejb-jar.xml

Entity Class

Hbernate Programming Model

POJO Beans

Mapping File

(optional)

• EJB 2.1

Complex Programming Model

Boilerplate code

Needs heavyweight app server

Persistence is not standardized

No support for Entity Inheritance

• Hibernate

Entity classes are POJOs

No dependency on API

No EJB container required

No XML required (use Java 5 Annotations)

Robust support for Inheritance Mappings

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 13/68

Hibernate Benefits

• Transparent & Declarative

Persistence

• Productivity

• Maintainability• Performance

• Vendor Independence

Presentation Tier 

Persistence Tier 

Business Tier 

DB

Java

Developers

DBAs

HibernateObject-relational

 paradigm synchronization

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 14/68

Hibernate Goals

• Do less work and have a happy DBA.

• No error prone JDBC code is required.

No manual handling of JDBC ResultSet

No Object Conversion

No hard coded SQL No Value Object Design Pattern

No preexisting DB schema required

No need to re-factor to support different DB vendors

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 15/68

Hibernate Mission Statement

Defining Transparent Persistence

• Any class can be a persistent class.

• No interfaces have to be implemented.• No persistent superclasses have to be extended.

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 16/68

Hibernate- The Big Picture

•  Annotations- new Java language feature introduced in Java SE 5.

• Hibernate Annotations + Hibernate Entity Manager = EJB 3.0 JPA sub spec

Java SE 1.4

Hibernate Core

XML Metadata

Java SE 5.0

Hibernate Core

XML Metadata

Entity Manager 

 Annotations

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 17/68

Architecture

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 18/68

Architecture

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 19/68

SessionFactory

• A thread-safe global object.

• There’s one SessionFactory per DB. 

• Creating a SessionFactory is expensive to create.

• Factory for Sessions.

• Instantiated once!

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 20/68

Session

• A single-threaded, short lived object representing

conversation btw the app and the persistent store.

• A non-threadsafe object that performs a single unit of work.

• Wraps a JDBC connection.• Acts as a factory for transactions.

• Is inexpensive to create!

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 21/68

Transaction

• A single-threaded, short lived object that represents an

atomic unit of work.

• Abstracts app from underlying JDBC transaction.

• A Session might span several Transactions in some cases.

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 22/68

First Hibernate Application

• Following steps are involved in developing a Hibernatepowered O/R mapping app:

1. Create POJO Bean (Entity Class)

2. Write Mapping File

3. Write Hibernate Configuration File

4. Prepare Hibernate Startup and Helper Class

5. Write the Client Code

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 23/68

Creating POJO Beans 

• Persistent classes are implemented as

POJO beans.

• Not all instances of a persistent class are considered to

be in the persistent state - an instance may instead

be transient or detached

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 24/68

POJO Programming Rules 

• Implement a no-argument constructor.

• Provide a default constructor with at least package

visibility.

• The no-argument constructor is required to

instantiate an object of this class through

reflection.

• Provide an identifier property (optional)

This property maps to the primary key column of a

database table

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 25/68

POJO Programming Rules 

• Prefer non-final classes (optional) 

• Declare accessors and mutators for persistent

fields (optional)

Hibernate can also access fields directly, the benefit of 

accessor methods is robustness for refactoring

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 26/68

Mapping File 

• What is a mapping file?• Hibernate needs to know how to load and store objects

of the persistent class. This is where the Hibernate

mapping file comes into play.• The mapping file tells Hibernate what table in the

database it has to access, and what columns in that

table it should use.

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 27/68

Structure of a Mapping File 

• How does the Hibernate mapping file look like?

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-

3.0.dtd">

<hibernate-mapping>[...]

</hibernate-mapping>

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 28/68

Structure of a Mapping File 

• Between the two hibernate-mapping tags, include a classelement. All persistent entity classes need such a

mapping, to a table in the SQL database:

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

<class name="Employee" table="IBM_EMPLOYEE">

…. 

</class>

</hibernate-mapping>

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 29/68

Generating DB row Identifier 

<id name="empid" column="EMP_ID">

<generator class="native"/>

</id>

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 30/68

Persisting Class properties 

<property name="empName" column="EMP_NAME"

length="40" type="string" />

<property name="empDesg" column="EMP_DESG"

type="string" />

<property name="salary" column="EMP_SAL" />

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 31/68

Mapping File 

• What should be the name of the mappingfile?

• The naming of mapping files can be arbitrary, howeverthe hbm.xml suffix is a convention in the Hibernate

developer community.

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 32/68

Mapping File 

• Where should be the mapping file

located?The mapping file should be present in the classpath.

• This mapping file should be saved as

Employee.hbm.xml, right in the directory next to the

Employee Java class source file.

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 33/68

Mapping File 

• Where is the mapping file referred from?All mapping files are referred from Hibernate configuration

file

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 34/68

Hibernate Configuration 

• What’s the purpose of Hibernateconfiguration file?

• Hibernate is the layer in your application which

connects to this database, so it needs connectioninformation.

• The connections are made through a JDBC connection

pool, which we also have to configure.

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 35/68

Hibernate Configuration 

• What’s the name of Hibernateconfiguration file?

• For Hibernate's configuration, we can use a simple

hibernate.properties file, a slightly moresophisticated

• hibernate.cfg.xml file, or even complete

programmatic setup. Most users prefer the XML

configuration file:

f b f

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 36/68

Structure of Hibernate Configuration

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

…… 

</session-factory>

</hibernate-configuration>

f ib fi i

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 37/68

Structure of Hibernate Configuration

• If you have several databases, use several <session-

factory> configurations, usually in several

configuration files (for easier startup).

• The dialect property element specifies the particularSQL variant Hibernate generates.

• The hbm2ddl.auto option turns on automatic

generation of database schemas - directly into thedatabase

S f Hib C fi i

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 38/68

Structure of Hibernate Configuration

Where should the configuration file placed?• Copy the Hibernate configuration file into the source

directory, so it will end up in the root of the classpath.

• Hibernate automatically looks for a file called 

hibernate.cfg.xml in the root of the classpath, on startup.

b d l

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 39/68

Hibernate Startup and Helper

• Hibernate startup requires building a global SessionFactory object and to store it somewhere for easy access in

application code.

• We’ll use a class that uses static singleton pattern.

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 40/68

 

Demo 1

Takeaway: Learn how to write a simple HibernateApplication

Hibernate_StartedApp

Obj S

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 41/68

Object States

Transient

Persistent

Detached

new

GC

Obj S

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 42/68

Object States

• Transient  - an object is transient if it has just beeninstantiated using the new operator, and it is not

associated with a Hibernate Session.

• It has no persistent representation in the database andno identifier value has been assigned.

• Transient instances will be destroyed by the garbage

collector if the application doesn't hold a reference

anymore.

Obj S

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 43/68

Object States

• Persistent - a persistent instance has a representation in thedatabase and an identifier value. It might just have been

saved or loaded, however, it is by definition in the scope of a

Session.

• Hibernate will detect any changes made to an object in

persistent state and synchronize the state with the database

when the unit of work completes.

Obj t St t

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 44/68

Object States

• Detached  - a detached instance is an object that has beenpersistent, but its Session has been closed.

• A detached instance can be reattached to a new Session at a

later point in time, making it (and all the modifications)

persistent again.

H t k Obj t P i t t

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 45/68

How to make Objects Persistent

• Newly instantiated instances of a a persistent class areconsidered transient by Hibernate.

• We can make a transient instance persistent by associating it

with a session and calling save().

• Long generatedId = (Long) sess.save(fritz);

H t L d P i t t Obj t

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 46/68

How to Load Persistent Objects

• The load() methods of Session gives you a way toretrieve a persistent instance if you already know its

identifier.

• load() takes a class object and will load the stateinto a newly instantiated instance of that class, in

persistent state.

• Example

Cat fritz = (Cat) sess.load(Cat.class, generatedId);

Note that load() will throw an ObjectNotFoundException 

if there is no matching database row

L di i t t bj t ith t()

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 47/68

Loading persistent objects with get()

• If you are not certain that a matching row exists,

you should use the get() method, which hits the

database immediately and returns null if there is no

matching row. Example:Cat cat = (Cat) sess.get(Cat.class, id);

if (cat==null) {

cat = new Cat();sess.save(cat, id);

}

return cat;

L d() t()

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 48/68

Load() vs. get()

• If you are not certain that a matching row exists, youshould use the get() method, which hits the database

immediately and returns null if there is no matching

row.

• The load() method, on the other hand, will not hit the

DB if the object in question can be found in the

persistent context. Else, it’ll throw an

ObjectNotFoundException.

Re loading Objects

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 49/68

Re-loading Objects

• It is possible to re-load an object and all its collections at anytime, using the refresh() method

Modifying persistent objects

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 50/68

Modifying persistent objects

• Transactional persistent instances (ie. objectsloaded, saved, created or queried by the Session)

may be manipulated by the application and any

changes to persistent state will be persisted when

the Session is flushed 

• There is no need to call a particular method (like

update(), which has a different purpose) to make

your modifications persistent.

Session Flushing

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 51/68

Session Flushing

• From time to time the Session will execute the SQL

statements needed to synchronize the JDBC

connection's state with the state of objects held in

memory. This process, flush, occurs by default at the

following points

• before some query executions 

• from org.hibernate.Transaction.commit() 

• from Session.flush() 

Reattaching Detached Objects

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 52/68

Reattaching Detached Objects

• Modifying an object after the session is closed has no

effect on it's persistence state in the DB, the object is

Detached; you can reattach a detached object to a new

session by calling update() on the detached object

Deleting persistent objects

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 53/68

Deleting persistent objects

• Session.delete() will remove an object's state from the

database. Of course, your application might still hold a

reference to a deleted object.

• It's best to think of delete() as making a persistentinstance transient.

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 54/68

 

Demo 2

Takeaway: Learn how to deal with thepersistent state of an object

Hibernate_ObjectPersistence

Object Equality

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 55/68

Object Equality

• The problem stems from differences betweenobject identity in the virtual machine (VM) and

object identity in the database.

• From different parts of a concurrent running

application, you might have two objects on the

heap even though the object state is pulled from

a single tuple in a DB.

Overriding equals() and hasCode()

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 56/68

Overriding equals() and hasCode()

• Hibernate guarantees equivalence of persistentidentity (database row) and Java identity only inside

a particular session scope. So as soon as we mix

instances retrieved in different sessions, we must

implement equals() and hashCode() if we wish tohave meaningful semantics

equals() Implementation

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 57/68

equals() Implementation

public boolean equals(Object other) {

if (this == other) return true;

if ( !(other instanceof Person) ) return false;

final Person aPerson = (Person) other;

if ( !aPerson.getFirstName().equals( this.getFirstName() ) )

return false;

if ( !aPerson.getLastName().equals( this.getLastName() ) )

return false;

return true;

}

Key Generation

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 58/68

Key Generation

<id name="id" column="ID">

<generator class="assigned" />

</id>

The optional <generator> child element names a Java classused to generate unique identifiers for instances of the

persistent class.

assigned is the default strategy which lets the application to

assign an identifier to the object before save() is called

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 59/68

 

Takeaway: Learn how to write a basic Hibernate

mapping file

Hibernate_BasicMappings

Mapping Id Field

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 60/68

Mapping Id Field

• Use id element

• Use generator subelement with class attribute,

which specifies the key generation scheme

<class name="Person">

<id name="id" type="int">

<generator class="increment "/>

</id>… 

</class>

Key Generation Scheme via class

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 61/68

y

attribute

• class=”increment” 

 – It generates identifiers of type long, short or int that are

unique only when no other process is inserting data into the

same table. It should not the used in the clustered

environment.

● class=”assigned” 

 – Lets the application to assign an identifier to the object

before save() is called. This is the default strategy if no

<generator> element is specified.

● class=”native” 

 – It picks identity, sequence or hilo depending upon the

capabilities of the underlying database.

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 62/68

 

Takeaway: Learn how generate primary keys in

DB table

Hibernate_IdGeneration

Composite Key

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 63/68

Composite Key

• For a table with composite key, you can multiple

properties with the <composite-id> tag in the

mapping file.

• The persistent class must implement the Serializable 

marker interface and override equals() and

hashCode() methods.

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 64/68

 

Takeaway: Learn how generate composite keys

Hibernate_CompositeKey

Hibernate DAO

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 65/68

Hibernate DAO

• DAO pattern

 – Separation of data access (persistence) logic from

business logic

 – Enables easier replacement of database without

affecting business logic

• DAO implementation strategies

 – Domain DAO interface and implementation – Domain DAO concrete classes

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 66/68

 

Takeaway: Learn how to segregate Database

access code with DAO pattern

Hibernate_DAO

Property Join

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 67/68

Property Join

• With Hibernate, you can move some properties to adifferent table using <join table> element.

• Using the <join> element, it is possible to map

properties of one class to several tables.

Configuring a Connection Pool

7/29/2019 Hibernate 68

http://slidepdf.com/reader/full/hibernate-68 68/68

Configuring a Connection Pool

• Code Snippet

<property name="c3p0.min_size">5</property>

<property name="c3p0.max_size">20</property>

<property name="c3p0.timeout">1800</property>

<property name="c3p0.max_statements">50</property>