Presentation is loading. Please wait.

Presentation is loading. Please wait.

An Introduction to Object/Relational Persistence and Hibernate Yi Li 2009.11.20.

Similar presentations


Presentation on theme: "An Introduction to Object/Relational Persistence and Hibernate Yi Li 2009.11.20."— Presentation transcript:

1 An Introduction to Object/Relational Persistence and Hibernate Yi Li 2009.11.20

2 The Book Java Persistence with Hibernate – Gavin King, the founder of Hibernate open source project – Christian Bauer, core developer Gavin King

3 Outline Understanding Object/Relational Persistence Understanding Hibernate – Part I: Mapping – Part II: Processing Designing the Persistence Layer

4 Understanding Object/Relational Persistence Persistence in object-oriented applications The problem The solution Introducing Hibernate

5 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

6 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

7 A Mismatch Problem Object-oriented business domain model – class, object – composition, inheritance, polymorphism… Relational persistent model – table, row, column – restriction, projection, join…

8 The Object/Relational Paradigm Mismatch Problem The problem of… – Granularity – Subtypes – Identity – Associations – Data navigation

9 Granularity Mismatch Class: several levels of granularity Database: only 2 levels (table and column) User Address zipcode: String street: String city: String > USER USERNAME ADDRESS_STREET ADDRESS_CITY ADDRESS_STATE ADDRESS_COUNTRY ADDRESS_ZIPCODE

10 Subtypes Mismatch OO – Type inheritance – Polymorphism and polymorphic association Relational DB – Table inheritance ? – Polymorphic query ? BillingDetails CreditCard BankAccount User 1..*

11 Identity Mismatch Object – identity: a == b – equality: a.equals(b) Database – identity: a.table_and_row == b.table_and_row IDNAMEAGEPWD ………… 3Mark2212345 ………… a a’ b b’

12 Associations Mismatch OO – one-to-one – one-to-many – many-to-many Relational DB – foreign key (actually a many-to-one) IDNAMESCHOOL_ID > 1Yi Li1 2Mark1 IDNAME 1EECS 2Chemistry 3History StudentSchool

13 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

14 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

15 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

16 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 

17 Why not object-oriented database systems – data independence  – current deployment environments  Why not XML persistence – data management  – object/hierarchical mismatch

18 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

19 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

20 Understanding Hibernate Mapping (Examples) – Inheritance – Associations – Polymorphism Persistent Object Processing

21 Fundamental Concepts of Mapping Fine-grained business model – More classes than tables Surrogate primary key Entity and value type > User > Address zipcode: String street: String city: String > USER ID > NAME ADDRESS_STREET ADDRESS_CITY ADDRESS_ZIPCODE id: Long name: String Surrogate PK

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

23 Table per Concrete Class BillingDetails CreditCardBankAccount User 1..* owner: String number: String expMonth: String expYear: String account: String bankname: String > BANK_ACCOUNT BA_ID > OWNER ACCOUNT BANKNAME > CREDIT_CARD CC_ID > OWNER NUMBER EXP_MONTH EXP_YEAR Advantage – Simplest Drawbacks – Poly-associations *  – Poly-query  – Schema evolution  *: Hibernate can implement this

24 Table per Class Hierarchy BillingDetails CreditCardBankAccount User 1..* owner: String number: String expMonth: String expYear: String account: String bankname: String > BILLING_DETAILS BD_ID > BD_TYPE > OWNER CC_NUMBER CC_EXP_MONTH CC_EXP_YEAR BA_ACCOUNT BA_BANKNAME Advantage – Performance – Simplicity – Polymorphism support Drawbacks – Loss of data integrity – Denormalized schema

25 Table per Class BillingDetails CreditCardBankAccount User 1..* owner: String number: String expMonth: String expYear: String account: String bankname: String > BANK_ACCOUNT BA_ID > > ACCOUNT BANKNAME > CREDIT_CARD CC_ID > > NUMBER EXP_MONTH EXP_YEAR > BILLING_DETAILS BD_ID > OWNER Advantage – Normalized schema – Data integrity – Polymorphism support Drawbacks – Performance 

26 Mapping 1-to-1 Association Shared Primary Key Strategy > USER USER_ID > NAME AGE PASSWORD … > CONTACT_INFO CI_ID > > EMAIL … Unique Foreign Key Strategy > USER USER_ID > USER_CONTACT_ID > > NAME AGE PASSWORD … > CONTACT_INFO CI_ID > EMAIL …

27 Mapping One-to-many Associations with Join Tables > ITEM ITEM_ID > NAME DESCRIPTION PRICE … > USER USER_ID > NAME … > ITEM_BUYER ITEM_ID > > > USER_ID > > ItemUser 0..*1 USER_IDITEM_ID 11 12 23 ITEM_BUYER

28 Mapping Many-to-many Associations with Join Tables > ITEM ITEM_ID > NAME DESCRIPTION PRICE … > CATEGORY CATEGORY_ID > NAME … > CATEGORIZED_ITEM ITEM_ID > > CATEGORY_ID > > ItemCategory 0..*1..* CATEGORY_IDITEM_ID 11 12 21 CATEGORIZED_ITEM

29 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

30 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

31 4. Concurrent access control – Deal with the transaction isolation issues D1 1. UPDATE 2. UPDATE 3. COMMIT 4. ROLLBACK Tx A Tx B D1 1. UPDATE 2. SELECT 4. COMMIT 3. ROLLBACK Tx A Tx B D1 1. SELECT 2. UPDATE 3. COMMIT Tx A Tx B D1 4. SELECT D1D2 1. SELECT 2. INSERT 3. COMMIT Tx A Tx B D1 D2 4. SELECT Lost Update Unrepeatable Read Dirty Read Phantom Read

32 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

33 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

34 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

35 Design Persistent Layer: the Generic DAO Pattern GenericDAO findById(ID id) findAll() findByExample(T exm) makePersistent(T entity) ItemDAO getComments(Long id) UserDAO GenericDAOHibernateImpl ItemDAOHibernateImpl UserDAOHibernateImpl InterfacesConcrete Classes

36 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); … true return new HibernateFactory(true); config.xml


Download ppt "An Introduction to Object/Relational Persistence and Hibernate Yi Li 2009.11.20."

Similar presentations


Ads by Google