1 / 36

An Introduction to Object/Relational Persistence and Hibernate

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

claral
Download Presentation

An Introduction to Object/Relational Persistence and Hibernate

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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 • Persistencein 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 <<Table>> USER USERNAME ADDRESS_STREET ADDRESS_CITY ADDRESS_STATE ADDRESS_COUNTRY ADDRESS_ZIPCODE Address zipcode: String street: String city: String

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

  11. Identity Mismatch • Object • identity: a == b • equality: a.equals(b) • Database • identity: a.table_and_row == b.table_and_row 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) Student School

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

  22. Mapping Class Inheritance • Mapping strategies • Table per concrete class • Table per class hierarchy • Table per class

  23. 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

  24. 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

  25. 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

  26. 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

  27. 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

  28. 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

  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 proceduresallow 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. 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

  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 Interceptors, Utility, and Helper Classes Business Layer Persistent Layer Provides abstraction and unified data access operations Database

  35. 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

  36. 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>

More Related