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

Slides:



Advertisements
Similar presentations
V 6, Mats Strandberg ORM With Hibernate.
Advertisements

An Object/Relational Mapping tool Free and open source Simplifies storage of object data in a relational database Removes the need to write and maintain.
Chapter 10: Designing Databases
.NET Database Technologies: Open-Source Frameworks.
Management Information Systems, Sixth Edition
GI Systems and Science January 30, Points to Cover  Recap of what we covered so far  A concept of database Database Management System (DBMS) 
Hibernate 1. Introduction ORM goal: Take advantage of the things SQL databases do well, without leaving the Java language of objects and classes. ORM.
Database management concepts Database Management Systems (DBMS) An example of a database (relational) Database schema (e.g. relational) Data independence.
Object Relational Mapping. What does ORM do? Maps Object Model to Relational Model. Resolve impedance mismatch. Resolve mapping of scalar and non-scalar.
Data Management Design
Database Features Lecture 2. Desirable features in an information system Integrity Referential integrity Data independence Controlled redundancy Security.
ORM Object-Relational Mapping 1. Object Persistence Persistence is the ability of an object to survive the lifecycle of the process, in which it resides.
Mgt 20600: IT Management & Applications Databases Tuesday April 4, 2006.
An Introduction to Hibernate Matt Secoske
Data Persistence and Object-Relational Mapping Slides by James Brucker, used with his permission 1.
Data Access Patterns. Motivation Most software systems require persistent data (i.e. data that persists between program executions). In general, distributing.
IST Databases and DBMSs Todd S. Bacastow January 2005.
CSE446 S OFTWARE Q UALITY M ANAGEMENT Spring 2014 Yazılım ve Uyguluma Geliştirme Yöneticisi Orhan Başar Evren.
Enterprise Object Framework. What is EOF? Enterprise Objects Framework is a set of tools and resources that help you create applications that work with.
Information storage: Introduction of database 10/7/2004 Xiangming Mu.
Chapter 4 The Relational Model.
Agenda What is Hibernate Spring Integration Questions Overview
Maven for building Java applications By Nalin De Zoysa
What is Architecture  Architecture is a subjective thing, a shared understanding of a system’s design by the expert developers on a project  In the.
Data Access Patterns Some of the problems with data access from OO programs: 1.Data source and OO program use different data modelling concepts 2.Decoupling.
Geog 495 GIS Database Design Midterm review. Outlines 1.Database Concepts 2.Relational Database 3.Object-oriented Database 4.Entity-Relationship Diagram.
Object persistence with Hibernate in Decision Deck 1.1 Gilles Dodinet 2 nd Decision Deck Workshop 2008, February.
Shaowen Wang CyberInfrastructure and Geospatial Information Laboratory (CIGI) Department of Geography and National Center for Supercomputing Applications.
CHAPTER 14 USING RELATIONAL DATABASES TO PROVIDE OBJECT PERSISTENCE (ONLINE) © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database.
.NET Database Technologies: Data Models and Patterns.
Object/Relational Mapping with Hibernate Practical ORM.
Object Oriented Analysis and Design 1 Chapter 7 Database Design  UML Specification for Data Modeling  The Relational Data Model and Object Model  Persistence.
Object Persistence Design Chapter 13. Key Definitions Object persistence involves the selection of a storage format and optimization for performance.
Lecture2: Database Environment Prepared by L. Nouf Almujally 1 Ref. Chapter2 Lecture2.
© 2011 Pearson Education, Inc. Publishing as Prentice Hall 1 Chapter 14 Using Relational Databases to Provide Object Persistence (Overview) Modern Database.
Hibernate Persistence. What is Persistence Persist data to database or other storage.  In OO world, persistence means persist object to external storage.
Relational Database. Database Management System (DBMS)
1 Mapping to Relational Databases Presented by Ramona Su.
Chapter 38 Persistence Framework with Patterns 1CS6359 Fall 2011 John Cole.
1 CS 430 Database Theory Winter 2005 Lecture 2: General Concepts.
Data resource management
A U.S. Department of Energy Office of Science Laboratory Operated by The University of Chicago Argonne National Laboratory Office of Science U.S. Department.
Topic : Hibernate 3:Advanced ORM Kaster Nurmukan.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 16 Using Relational Databases.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
Hibernate Basics. Basics What is persistence? Persistence in Object Oriented Applications? Paradigm Mismatch.  The Problem of Granularity.  The Problem.
Object storage and object interoperability
ESG-CET Meeting, Boulder, CO, April 2008 Gateway Implementation 4/30/2008.
Mapping Objects ↔Relational DB. The Problem with Databases Databases store data in rows in tables, which are not like objects. We can simulate object.
PowerPoint Presentation for Dennis, Wixom, & Tegarden Systems Analysis and Design with UML, 5th Edition Copyright © 2015 John Wiley & Sons, Inc. All rights.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Singleton Academy, Pune. Course syllabus Singleton Academy Pune – Course Syllabus1.
ORM Basics Repository Pattern, Models, Entity Manager Ivan Yonkov Technical Trainer Software University
Faeez, Franz & Syamim.   Database – collection of persistent data  Database Management System (DBMS) – software system that supports creation, population,
CS422 Principles of Database Systems Object-Relational Mapping (ORM) Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA (I) Chengyu Sun California State University, Los Angeles.
Hibernate Java Persistence API. What is Persistence Persistence: The continued or prolonged existence of something. Most Applications Achieve Persistence.
HIBERNATE/Java Overview of technology for Hibernate by محمد حسن کاظمی پوران Master : M.M.Nematollahi.
Introduction to DBMS Purpose of Database Systems View of Data
New Technology: Why, What ,How
Don't Know Jack About Object-Relational Mapping?
Chengyu Sun California State University, Los Angeles
Chapter 1 Introduction.
POOL persistency framework for LHC
Object/Relational Mapping with Hibernate
ARCH-1: Application Architecture made Simple
Data Model.
Introduction to DBMS Purpose of Database Systems View of Data
Object Relational Mapping Tools
Presentation transcript:

An Introduction to Object/Relational Persistence and Hibernate Yi Li

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: String street: String city: String > USER USERNAME ADDRESS_STREET ADDRESS_CITY ADDRESS_STATE ADDRESS_COUNTRY ADDRESS_ZIPCODE

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

Identity Mismatch Object – identity: a == b – equality: a.equals(b) Database – identity: a.table_and_row == b.table_and_row IDNAMEAGEPWD ………… 3Mark ………… 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) IDNAMESCHOOL_ID > 1Yi Li1 2Mark1 IDNAME 1EECS 2Chemistry 3History StudentSchool

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 > User > Address zipcode: String street: String city: String > USER ID > NAME ADDRESS_STREET ADDRESS_CITY ADDRESS_ZIPCODE id: Long name: String Surrogate PK

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

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

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

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 

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

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 ITEM_BUYER

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

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 findById(ID id) findAll() findByExample(T exm) makePersistent(T entity) ItemDAO getComments(Long id) UserDAO GenericDAOHibernateImpl ItemDAOHibernateImpl UserDAOHibernateImpl InterfacesConcrete 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); … true return new HibernateFactory(true); config.xml