Transcript
Page 1: An Introduction to Object/Relational Persistence and  Hibernate

An Introduction to Object/Relational Persistence and Hibernate

Yi Li2009.11.20

Page 2: An Introduction to Object/Relational Persistence and  Hibernate

The Book

• Java Persistence with Hibernate– Gavin King, the founder of Hibernate open source

project– Christian Bauer, core developer

Gavin King

Page 3: An Introduction to Object/Relational Persistence and  Hibernate

Outline

• Understanding Object/Relational Persistence• Understanding Hibernate– Part I: Mapping – Part II: Processing

• Designing the Persistence Layer

Page 4: An Introduction to Object/Relational Persistence and  Hibernate

Understanding Object/Relational Persistence

• Persistence in object-oriented applications• The problem• The solution• Introducing Hibernate

Page 5: An Introduction to Object/Relational Persistence and  Hibernate

What is Object/Relational Persistence

• The states of interconnected objects need to be stored to a relational database using SQL, and objects with the same state can be re-created at some point in the future

Page 6: An Introduction to Object/Relational Persistence and  Hibernate

Why Object and Relational DB

• Business Logic– Object-oriented concepts largely improves code

reuse and maintainability

• Business Data– Relational databases are flexible and robust

approach to data management, due to the complete and consistent theoretical foundation of the relational data model

Page 7: An Introduction to Object/Relational Persistence and  Hibernate

A Mismatch Problem

• Object-oriented business domain model– class, object– composition, inheritance, polymorphism…

• Relational persistent model– table, row, column– restriction, projection, join…

Page 8: An Introduction to Object/Relational Persistence and  Hibernate

The Object/Relational Paradigm Mismatch Problem

• The problem of…– Granularity– Subtypes– Identity– Associations– Data navigation

Page 9: An Introduction to Object/Relational Persistence and  Hibernate

Granularity Mismatch

• Class: several levels of granularity• Database: only 2 levels (table and column)

User

Address

zipcode: Stringstreet: Stringcity: String

<<Table>>USER

USERNAMEADDRESS_STREETADDRESS_CITYADDRESS_STATEADDRESS_COUNTRYADDRESS_ZIPCODE

Page 10: An Introduction to Object/Relational Persistence and  Hibernate

Subtypes Mismatch• OO– Type inheritance– Polymorphism and polymorphic association

• Relational DB– Table inheritance ? – Polymorphic query ?

BillingDetails

CreditCard BankAccount

User1..*

Page 11: An Introduction to Object/Relational Persistence and  Hibernate

Identity Mismatch

• Object– identity: a == b– equality: a.equals(b)

• Database– identity: a.table_and_row == b.table_and_row

ID NAME AGE PWD… … … …

3 Mark 22 12345

… … … …

a

a’

b

b’

Page 12: An Introduction to Object/Relational Persistence and  Hibernate

Associations Mismatch• OO– one-to-one– one-to-many– many-to-many

• Relational DB– foreign key (actually a many-to-one)

ID NAME SCHOOL_ID <<FK>>

1 Yi Li 1

2 Mark 1

ID NAME

1 EECS

2 Chemistry

3 History

Student School

Page 13: An Introduction to Object/Relational Persistence and  Hibernate

Data Navigation Mismatch• OO– one by one: follow the pointers between objects

• Relational DB– strive to minimize the number of requests to DB– sophisticated mechanisms for retrieving and updating data

aUser.getBillingDetails().getAccountNumber();

select * from USERS u left outer join BILLING_DETAILS bd on bd.USER_ID = u.USER_ID where u.USER_ID = 3

Page 14: An Introduction to Object/Relational Persistence and  Hibernate

Cost of the Mismatch Problem

• In authors’ experience, 30% of Java application code is to handle the problems, and result doesn’t feel right

• Bended and twisted business entities to match the SQL database schema, which often doesn’t follow OO principles very well

Page 15: An Introduction to Object/Relational Persistence and  Hibernate

The solution• The 5 problems fall into 2 categories– Structural (static)– Behavioral (dynamic)

• The solution is Object / Relational Mapping (ORM)– Using metadata to describe object/table mapping– Persistent object management, transaction and

concurrency support– Automated and transparent

Page 16: An Introduction to Object/Relational Persistence and  Hibernate

Possible Alternatives & Why Not

• Why not serialization– a serialized network of interconnected objects can

only be accessed as a whole• large datasets • access / update a subset of objects • high concurrency support

Page 17: An Introduction to Object/Relational Persistence and  Hibernate

• Why not object-oriented database systems– data independence – current deployment environments

• Why not XML persistence– data management – object/hierarchical mismatch

Page 18: An Introduction to Object/Relational Persistence and  Hibernate

Introducing Hibernate

• Hibernate is a full ORM tool– Complete mapping support• Composition, inheritance, polymorphism

– Fully Transparent• No persistence-specific base classes & interfaces

needed in business layer– High Performance

Page 19: An Introduction to Object/Relational Persistence and  Hibernate

Hibernate and the Standards

• Java industry standards– Java Persistence API Specification (JPA)

• Developers from the Hibernate team joined the specification expert group early

• Hibernate is the recommended implementation for JPA

Page 20: An Introduction to Object/Relational Persistence and  Hibernate

Understanding Hibernate

• Mapping (Examples)– Inheritance– Associations– Polymorphism

• Persistent Object Processing

Page 21: An Introduction to Object/Relational Persistence and  Hibernate

Fundamental Concepts of Mapping

• Fine-grained business model– More classes than tables

• Surrogate primary key• Entity and value type

<<Entity>>User

<<Value>>Address

zipcode: Stringstreet: Stringcity: String

<<Table>>USER

ID <<PK>>NAMEADDRESS_STREETADDRESS_CITYADDRESS_ZIPCODE

id: Longname: String

Surrogate PK

Page 22: An Introduction to Object/Relational Persistence and  Hibernate

Mapping Class Inheritance• Mapping strategies– Table per concrete class– Table per class hierarchy– Table per class

Page 23: An Introduction to Object/Relational Persistence and  Hibernate

Table per Concrete ClassBillingDetails

CreditCard BankAccount

User1..*

owner: String

number: StringexpMonth: StringexpYear: String

account: Stringbankname: String

<<Table>>BANK_ACCOUNT

BA_ID <<PK>>OWNERACCOUNTBANKNAME

<<Table>>CREDIT_CARD

CC_ID <<PK>>OWNERNUMBEREXP_MONTHEXP_YEAR

• Advantage– Simplest

• Drawbacks– Poly-associations * – Poly-query – Schema evolution

*: Hibernate can implement this

Page 24: An Introduction to Object/Relational Persistence and  Hibernate

Table per Class HierarchyBillingDetails

CreditCard BankAccount

User1..*

owner: String

number: StringexpMonth: StringexpYear: String

account: Stringbankname: String

<<Table>>BILLING_DETAILS

BD_ID <<PK>>BD_TYPE <<Discriminator>>OWNERCC_NUMBERCC_EXP_MONTHCC_EXP_YEARBA_ACCOUNTBA_BANKNAME

• Advantage– Performance– Simplicity– Polymorphism support

• Drawbacks– Loss of data integrity – Denormalized schema

Page 25: An Introduction to Object/Relational Persistence and  Hibernate

Table per ClassBillingDetails

CreditCard BankAccount

User1..*

owner: String

number: StringexpMonth: StringexpYear: String

account: Stringbankname: String

<<Table>>BANK_ACCOUNT

BA_ID <<PK>> <<FK>>ACCOUNTBANKNAME

<<Table>>CREDIT_CARD

CC_ID <<PK>> <<FK>>NUMBEREXP_MONTHEXP_YEAR

<<Table>>BILLING_DETAILS

BD_ID <<PK>>OWNER

• Advantage– Normalized schema– Data integrity– Polymorphism support

• Drawbacks– Performance

Page 26: An Introduction to Object/Relational Persistence and  Hibernate

Mapping 1-to-1 Association• Shared Primary Key Strategy

<<Table>>USER

USER_ID <<PK>>NAMEAGEPASSWORD…

<<Table>>CONTACT_INFO

CI_ID <<PK>> <<FK>>EMAIL…

• Unique Foreign Key Strategy<<Table>>

USERUSER_ID <<PK>>USER_CONTACT_ID <<FK>> <<UNIQUE>>NAMEAGEPASSWORD…

<<Table>>CONTACT_INFO

CI_ID <<PK>>EMAIL…

Page 27: An Introduction to Object/Relational Persistence and  Hibernate

Mapping One-to-many Associations with Join Tables

<<Table>>ITEM

ITEM_ID <<PK>>NAMEDESCRIPTIONPRICE…

<<Table>>USER

USER_ID <<PK>>NAME…

<<Table>>ITEM_BUYER

ITEM_ID <<PK>> <<FK>> <<UNIQUE>>USER_ID <<PK>> <<FK>>

Item User0..* 1

USER_ID ITEM_ID

1 1

1 2

2 3

ITEM_BUYER

Page 28: An Introduction to Object/Relational Persistence and  Hibernate

Mapping Many-to-many Associations with Join Tables

<<Table>>ITEM

ITEM_ID <<PK>>NAMEDESCRIPTIONPRICE…

<<Table>>CATEGORY

CATEGORY_ID <<PK>>NAME…

<<Table>>CATEGORIZED_ITEM

ITEM_ID <<PK>> <<FK>> CATEGORY_ID <<PK>> <<FK>>

Item Category0..* 1..*

CATEGORY_ID ITEM_ID

1 1

1 2

2 1

CATEGORIZED_ITEM

Page 29: An Introduction to Object/Relational Persistence and  Hibernate

Other Features of Hibernate Mapping• Schema exporting

• Automated support of polymorphic associations

• Flexible type mapping system– Built-in types– Custom mapping types

• Fully customizable SQL and stored procedures allow developers to integrate legacy databases without changing business objects– Only the mapping metadata needs to be changed

Page 30: An Introduction to Object/Relational Persistence and  Hibernate

Issues in Persistent Object Processing: At a Glance

• 1. Transparent dirty checking• 2. Object identity == database identity– What if the application modifies two different

instances that both represent the same row in the end of a transaction?

• 3. Database transaction support

Page 31: An Introduction to Object/Relational Persistence and  Hibernate

• 4. Concurrent access control– Deal with the transaction isolation issues

D1 D1

1. UPDATE

2. UPDATE

3. COMMIT

4. ROLLBACK

Tx A

Tx B

D1 D1

1. UPDATE

2. SELECT 4. COMMIT

3. ROLLBACK

Tx A

Tx B

D1 D1

1. SELECT

2. UPDATE

3. COMMIT

Tx A

Tx B

D1

4. SELECT

D1 D2

1. SELECT

2. INSERT

3. COMMIT

Tx A

Tx B

D1D2

4. SELECT

Lost Update

Unrepeatable Read

Dirty Read

Phantom Read

Page 32: An Introduction to Object/Relational Persistence and  Hibernate

• 5. Sharing objects in different connections• 6. Transitive persistence• 7. Batch operations• 8. Data filtering and interception• 9. Optimizing data fetching and caching

strategies– In the context of concurrency

• 10. Object-based query language– ‘SQL’ in terms of object

• 11. Optimizing query performance

Page 33: An Introduction to Object/Relational Persistence and  Hibernate

The Last But Not the Least…

• Hibernate is a fully transparent solution to object persistence– You can design and implement business entities

and business logic as if there is no Hibernate at all

Page 34: An Introduction to Object/Relational Persistence and  Hibernate

You Need a Persistence Layer

• A typical layered architecture

Presentation Layer

Business Layer

Persistent Layer

Database

Interceptors, Utility, and

Helper Classes

Provides abstraction and unified data access operations

Page 35: An Introduction to Object/Relational Persistence and  Hibernate

Design Persistent Layer: the Generic DAO Pattern

GenericDAO<T, ID>findById(ID id)findAll()findByExample(T exm)makePersistent(T entity)

ItemDAO<Item, Long>getComments(Long id)

UserDAO<Item, Long>

GenericDAOHibernateImpl

ItemDAOHibernateImpl

UserDAOHibernateImpl

Interfaces Concrete Classes

Page 36: An Introduction to Object/Relational Persistence and  Hibernate

Using Data Access Objects in Business Logic

Long itemId = …;DAOFactory factory = DAOFactory.getFactory();ItemDAO itemDAO = factory.getItemDAO();

Item item = itemDAO.findById(itemId);List comments = itemDAO.getComments(itemId);…

<dao-factory> <class = “com.xxx.dao.HibernateFactory”> <param name=“option1”>true</param></dao-factory>

return new HibernateFactory(true);config.xml


Recommended