380 likes | 536 Views
An Introduction to Object/Relational Persistence and Hibernate. Yi Li 2009.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
E N D
An Introduction to Object/Relational Persistence and Hibernate Yi Li 2009.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 • Persistencein 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 <<Table>> USER USERNAME ADDRESS_STREET ADDRESS_CITY ADDRESS_STATE ADDRESS_COUNTRY ADDRESS_ZIPCODE Address zipcode: String street: String city: String
Subtypes Mismatch • OO • Type inheritance • Polymorphism and polymorphic association • Relational DB • Table inheritance ? • Polymorphic query ? 1..* User BillingDetails CreditCard BankAccount
Identity Mismatch • Object • identity: a == b • equality: a.equals(b) • Database • identity: a.table_and_row == b.table_and_row 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) 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 Surrogate PK id: Long name: String <<Table>> USER ID <<PK>> NAME ADDRESS_STREET ADDRESS_CITY ADDRESS_ZIPCODE <<Value>> Address zipcode: String street: String city: String
Mapping Class Inheritance • Mapping strategies • Table per concrete class • Table per class hierarchy • Table per class
Table per Concrete Class 1..* BillingDetails User owner: String CreditCard BankAccount <<Table>> BANK_ACCOUNT <<Table>> CREDIT_CARD number: String expMonth: String expYear: String account: String bankname: String • Advantage • Simplest • Drawbacks • Poly-associations * • Poly-query • Schema evolution BA_ID <<PK>> OWNER ACCOUNT BANKNAME CC_ID <<PK>> OWNER NUMBER EXP_MONTH EXP_YEAR *: Hibernate can implement this
Table per Class Hierarchy 1..* BillingDetails User owner: String CreditCard BankAccount <<Table>> BILLING_DETAILS number: String expMonth: String expYear: String account: String bankname: String • Advantage • Performance • Simplicity • Polymorphism support • Drawbacks • Loss of data integrity • Denormalized schema BD_ID <<PK>> BD_TYPE <<Discriminator>> OWNER CC_NUMBER CC_EXP_MONTH CC_EXP_YEAR BA_ACCOUNT BA_BANKNAME
Table per Class 1..* BillingDetails User owner: String CreditCard BankAccount <<Table>> BANK_ACCOUNT <<Table>> BILLING_DETAILS <<Table>> CREDIT_CARD number: String expMonth: String expYear: String account: String bankname: String • Advantage • Normalized schema • Data integrity • Polymorphism support • Drawbacks • Performance BA_ID <<PK>> <<FK>> ACCOUNT BANKNAME CC_ID <<PK>> <<FK>> NUMBER EXP_MONTH EXP_YEAR BD_ID <<PK>> OWNER
Mapping 1-to-1 Association • Shared Primary Key Strategy <<Table>> USER <<Table>> USER <<Table>> CONTACT_INFO <<Table>> CONTACT_INFO USER_ID <<PK>> NAME AGE PASSWORD … USER_ID <<PK>> USER_CONTACT_ID <<FK>> <<UNIQUE>> NAME AGE PASSWORD … CI_ID <<PK>> <<FK>> EMAIL … CI_ID <<PK>> EMAIL … • Unique Foreign Key Strategy
Mapping One-to-many Associations with Join Tables 0..* 1 Item User <<Table>> ITEM <<Table>> USER <<Table>> ITEM_BUYER ITEM_ID <<PK>> NAME DESCRIPTION PRICE … USER_ID <<PK>> NAME … ITEM_ID <<PK>> <<FK>> <<UNIQUE>> USER_ID <<PK>> <<FK>> ITEM_BUYER
Mapping Many-to-many Associations with Join Tables 0..* 1..* Item Category <<Table>> ITEM <<Table>> CATEGORY <<Table>> CATEGORIZED_ITEM ITEM_ID <<PK>> NAME DESCRIPTION PRICE … CATEGORY_ID <<PK>> NAME … ITEM_ID <<PK>> <<FK>> CATEGORY_ID <<PK>> <<FK>> 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 proceduresallow 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
1. UPDATE 3. COMMIT 2. SELECT 4. COMMIT Tx A Tx A • 4. Concurrent access control • Deal with the transaction isolation issues D1 D1 D1 D1 4. ROLLBACK 3. ROLLBACK Tx B Tx B 2. UPDATE 1. UPDATE Lost Update Dirty Read 1. SELECT 4. SELECT 1. SELECT 4. SELECT Tx A Tx A D1 D1 D1 D1 D2 D1 D2 3. COMMIT 3. COMMIT Tx B Tx B 2. UPDATE 2. INSERT Unrepeatable 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 Interceptors, Utility, and Helper Classes Business Layer Persistent Layer Provides abstraction and unified data access operations Database
Design Persistent Layer: the Generic DAO Pattern GenericDAO<T, ID> findById(ID id) findAll() findByExample(T exm) makePersistent(T entity) GenericDAOHibernateImpl ItemDAO<Item, Long> ItemDAOHibernateImpl getComments(Long id) UserDAO<Item, Long> UserDAOHibernateImpl Interfaces Concrete Classes
Using Data Access Objects in Business Logic Long itemId = …; DAOFactory factory = DAOFactory.getFactory(); ItemDAOitemDAO = factory.getItemDAO(); Item item = itemDAO.findById(itemId); List comments = itemDAO.getComments(itemId); … return new HibernateFactory(true); config.xml • <dao-factory> • <class = “com.xxx.dao.HibernateFactory”> • <paramname=“option1”>true</param> • </dao-factory>