An Introduction to Object/Relational Persistence and Hibernate
description
Transcript of An Introduction to Object/Relational Persistence and Hibernate
An Introduction to Object/Relational Persistence and Hibernate
Yi Li2009.11.20
The Book
• Java Persistence with Hibernate– Gavin King, the founder of Hibernate open source
project– Christian Bauer, core developer
Gavin King
Outline
• Understanding Object/Relational Persistence• Understanding Hibernate– Part I: Mapping – Part II: Processing
• Designing the Persistence Layer
Understanding Object/Relational Persistence
• Persistence in object-oriented applications• The problem• The solution• Introducing 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
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
A Mismatch Problem
• Object-oriented business domain model– class, object– composition, inheritance, polymorphism…
• Relational persistent model– table, row, column– restriction, projection, join…
The Object/Relational Paradigm Mismatch Problem
• The problem of…– Granularity– Subtypes– Identity– Associations– Data navigation
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
Subtypes Mismatch• OO– Type inheritance– Polymorphism and polymorphic association
• Relational DB– Table inheritance ? – Polymorphic query ?
BillingDetails
CreditCard BankAccount
User1..*
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’
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
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
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
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
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
• Why not object-oriented database systems– data independence – current deployment environments
• Why not XML persistence– data management – object/hierarchical mismatch
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
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
Understanding Hibernate
• Mapping (Examples)– Inheritance– Associations– Polymorphism
• Persistent Object Processing
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
Mapping Class Inheritance• Mapping strategies– Table per concrete class– Table per class hierarchy– Table per class
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
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
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
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…
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
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
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
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
• 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
• 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
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
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
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
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