SlideShare a Scribd company logo
1 of 64
DESIGNING A
PERSISTENCE
FRAMEWORK WITH
PATTERNS
The Problem: Persistent
Objects
persistent object
 An object that can survive the process or
thread that created it. A persistent object
exists until it is explicitly deleted
ProductDescription
Storage Mechanisms and Persistent
Objects
 Object databases
 Relational databases
 others
The Solution: A Persistence Service
from a Persistence Framework
The framework should provide functions
such as:
 store and retrieve objects in a persistent
storage mechanism
 commit and rollback transactions
persistence framework
 general-purpose, reusable, and extendable
set of types that provides functionality to
support persistent objects
framework
 A set of collaborating abstract and
concrete classes that may be used as a
template to solve a related family of
problems. It is usually extended via
subclassing for application-specific
behavior
Key Ideas
Mapping
Object identity
Database mapper
Materialization and dematerialization
Caches
Transaction state of object
Transaction operations
Lazy materialization
Virtual proxies
The Representing
Objects as Tables
pattern
How do you map an object to a record
or relational database schema?
The Representing Objects as Tables
pattern
Manufacturer
name
city
...
...
name city
Now&Zen Mumbai
MANUFACTURER TABLE
: Manufacturer
name = Now&Zen
city = Mumbai
Celestial
Shortening
San Ramon
UML Data Modeling
Profile
«Table»
ProductDescription
«PK» OID : char(16)
Description : varchar(100)
...
«FK» Manu_OID : char(16)
«Table»
Manufacturer
«PK» OID : char(16)
Name : varchar(100)
City : varchar(50)
*
1
aggregate signifies a referential constraint: a ProductDescription
row can't exist without a related Manufacturer row
PK - primary key
FK - foreign key
对关系的存储设计
对泛化的存储设计
Method 1
Method 2a
Method 2b
object identifier
(OID)pattern
OID
xyz123
abc345
This is a simplified design.
In reality, the OID may be
placed in a Proxy class.
primary key
Manufacturer
city
name
oid : OID
...
...
name city
Now&Zen Mumbai
MANUFACTURER TABLE
: Manufacturer
city = Mumbai
name = Now&Zen
oid = xyz123
Celestial
Shortening
San Ramon
Accessing a Persistence
Service with a Facade
1
PersistenceFacade
...
getInstance() : PersistenceFacade
get( OID, Class ) : Object
put( OID, Object )
...
: DBProductsAdapter
1
: PersistenceFacade
pd = get(...)
// example use of the facade
OID oid = new OID("XYZ123");
ProductDescription pd = (ProductDescription) PersistenceFacade.getInstance().get( oid, ProductDescription.class );
Mapping Objects:
Database Mapper or
Database Broker Pattern
Who should be responsible for
materialization and dematerialization of
objects (for example, a
ProductDescription) from a persistent
store?
The PersistenceFacade—as true of all
facades—does not do the work itself,
but delegates requests to subsystem
objects.
 direct mapping
 persistent object class itself
 indirect mapping
 Database Broker pattern
 Database Mapper pattern
Metadata-Based
Mappers
class PersistenceFacade
{
/ / . . .
public Object get( OID oid, Class persistenceClass )
{
// an IMapper is keyed by the Class of the persistent object
IMapper mapper = (IMapper) mappers.get( persistenceClass );
// delegate
return mapper.get( oid );
}
//...
}
usage:
(Manufacturer) PersistenceFacade.getInstance().
get( manuOID, Manufacturer.class) );
each mapper gets and puts objects in its own unique way ,
depending on the kind of data store and format
1
PersistenceFacade
getInstance () : PersistenceFacade
get ( OID , Class ) : Object
put ( OID , Object )
...
ProductSpecification
RDBMapper
...
get ( OID ) : Object
put ( OID , Object )
...
ProductSpecification
FlatFileMapper
...
get ( OID ) : Object
put ( OID , Object )
...
Manufacturer
RDBMapper
...
get ( OID ) : Object
put ( OID , Object )
...
note that the Class as a
parameter is no longer
needed in this version of
get , as the class is
"hardwired " for a particular
persistent type
1
«interface»
IMapper
get (OID ) : Object
put ( OID , Object )
...
Class
UML notation : This is a qualified assocation . It means :
1. There is a 1-M association from PersistenceFacade to IMapper objects .
2. With a key of type Class , an IMapper is found (e.g., via a HashMap lookup )
Template Method
Pattern
GUIComponent
update()
repaint()
MyExcellentButton
repaint()
// this is the template method
// its algorithm is the unvarying part
public void update()
{
clearBackground();
// this is the hook method
// it is the varying part
repaint();
}
hook method
- varying part
- overriden in subclass
-may be abstract, or have
a default implementation
hook method overriden
- fills in the varying part of
the algorithm
HOLLYWOOD PRINCIPLE:
Don't call us, we'll call you
Note that the MyExcellentButton--repaint method is
called from the inherited superclass update
method. This is typical in plugging into a
framework class.
FRAMEWORK class
OUR class
template method
hook method
Framework Design with the Template Method
Pattern
 if (object in cache)
 return it
 else
 create the object from its representation in storage
 save object in cache
 return it
Abstract
PersistenceMapper
+ get ( OID ) : Object {leaf }
# getObjectFromStorage (OID ) : Object {abstract }
...
«interface»
IMapper
get (OID ) : Object
put ( OID , Object )
...
// template method
public final Object get ( OID oid )
{
obj := cachedObjects .get (oid );
if (obj == null )
{
// hook method
obj = getObjectFromStorage ( oid );
cachedObjects .put ( oid , obj );
}
return obj ;
} HOOK
TEMPLATE
How to use the Framework
ProductDescription
RDBMapper
# getObjectFromStorage(OID) : Object
Abstract
PersistenceMapper
+ get( OID) : Object {leaf}
# getObjectFromStorage(OID) : Object {abstract}
...
// template method
public final Object get( OID oid )
{
obj := cachedObjects.get(oid);
if (obj == null )
{
// hook method
obj = getObjectFromStorage( oid );
cachedObjects.put( oid, obj )
}
return obj
}
// hook method override
protected Object getObjectFromStorage( OID oid )
{
String key = oid.toString();
dbRec = SQL execution result of:
"Select * from PROD_DESC where key =" + key
ProductDescription pd = new ProductDescription();
pd.setOID( oid );
pd.setPrice( dbRec.getColumn("PRICE") );
pd.setItemID( dbRec.getColumn("ITEM_ID") );
pd.setDescrip( dbRec.getColumn("DESC") );
return pd;
}
IMapper
Further factoring out the varying and
unvarying parts of the algorithm.
Final Framework
1
«interface»
IMapper
get (OID ) : Object
put ( OID , Object )
...
Class
1
+ PersistenceFacade
getInstance () : PersistenceFacade
get ( OID , Class ) : Object
put ( OID , Object )
...
Abstract
PersistenceMapper
+ get ( OID ) : Object {leaf }
# getObjectFromStorage (OID ) : Object
...
Abstract
RDBMapper
+ AbstractRDBMapper (tableName )
# getObjectFromStorage (OID ) : Object {leaf }
# getObjectFromRecord (OID , DBRecord ) : Object
- getDBRecord (OID ) : DBRecord
Persistence
NextGen Persistence
ProductDescription
RDBMapper
+ ProductDescriptionRDBMapper (tableName )
# getObjectFromRecord (OID , DBRecord ) : Object
ProductDescription
FileWithXMLMapper
# getObjectFromStorage (OID ) : Object
Sale
RDBMapper
...
# getObjectFromRecord (OID , DBRecord ) : Object
ProductDescription
InMemoryTestDataMapper
# getObjectFromStorage (OID ) : Object
Abstract
PersistenceMapper
+ get( OID) : Object {leaf, guarded}
...
// Java
public final synchronized Object get( OID oid )
{ ... }
{guarded} means a "synchronized" method; that is,
only 1 thread may execute at a time within the
family of guarded methods of this object.
IMapper
Configuring Mappers
class MapperFactory
{
public IMapper
getProductSpecificationMapper(){...}
public IMapper getSaleMapper() {...}
}
class MapperFactory{
public Map getAllMappers( ) {...}
}
class PersistenceFacade{
private java.util.Map mappers =
MapperFactory.getlnstance( ).getAllMappers( );
}
ProductDescription
RDBMapper
# getObjectFromStorage(OID) : Object
Abstract
PersistenceMapper
+ get( OID) : Object {leaf}
# getObjectFromStorage(OID) : Object {abstract}
...
// template method
public final Object get( OID oid )
{
obj := cachedObjects.get(oid);
if (obj == null )
{
// hook method
obj = getObjectFromStorage( oid );
cachedObjects.put( oid, obj )
}
return obj
}
// hook method override
protected Object getObjectFromStorage( OID oid )
{
String key = oid.toString();
dbRec = SQL execution result of:
"Select * from PROD_DESC where key =" + key
ProductDescription pd = new ProductDescription();
pd.setOID( oid );
pd.setPrice( dbRec.getColumn("PRICE") );
pd.setItemID( dbRec.getColumn("ITEM_ID") );
pd.setDescrip( dbRec.getColumn("DESC") );
return pd;
}
IMapper
class ProductSpecificationRDBMapper extends …{
// hook method override
protected Object getObjectFromStorage( OID oid )
{
String key = oid.toString();
dbRec = SQL execution result of:
"Select * from PROD_SPEC where key =" + key
ProductSpecification ps = new ProductSpecification();
ps.setOID( oid );
ps.setPrice( dbRec.getColumn("PRICE") );
ps.setItemID( dbRec.getColumn("ITEM_ID") );
ps.setDescrip( dbRec.getColumn("DESC") );
return ps;
}
}
class RDBOperations
{
public ResultSet getProductDescriptionData( OID oid ) {...}
public ResultSet getSaleData( OID oid ) {...}
...
}
class ProductDescriptionRDBMapper extends
AbstractPersistenceMapper{
protected Object getObjectFromStorage( OID oid )
{
ResultSet rs =
RDBOperations.getInstance().getProductDescriptionData( oid );
ProductDescription ps = new ProductDescription();
ps.setPrice( rs.getDouble( "PRICE" ) );
ps.setOID( oid );
return ps;
}
Pattern: Cache
Management
to maintain materialized objects in a local
cache to improve performance
(materialization is relatively slow) and support
transaction management operations such as
a commit.
When objects are materialized, they are
placed in the cache, with their OID as the key.
Subsequent requests to the mapper for an
object will cause the mapper to first search
the cache, thus avoiding unnecessary
materialization
Transactional States
and the State Pattern
Persistent objects can be inserted,
deleted, or modified.
Operating on a persistent object (for
example, modifying it) does not cause
an immediate database update; rather,
an explicit commit operation must be
performed.
OldClean OldDirty
OldDelete
commit / delete
delete
New
[ from DB ]
[new (not from DB )]
save
commit / update
delete
rollback / reload
rollback / reload
commit / insert
State chart : PersistentObject
Legend :
New--newly created ; not in DB
Old--retrieved from DB
Clean --unmodified
Dirty--modified
Deleted
Persistence
Domain
ProductDescription
...
PersistentObject
oid : OID
timeStamp:
DateTime
commit()
delete()
rollback()
save()
...
GoF State pattern
Context/Problem
An object's behavior is dependent on its state, and its
methods contain case logic reflecting conditional
state-dependent actions. Is there an alternative to
conditional logic?
Solution
Create state classes for each state, implementing a
common interface. Delegate state-dependent
operations from the context object to its current state
object. Ensure the context object always points to a
state object reflecting its current state.
PersistentObject
oid : OID
state : PObjectState
commit()
delete()
rollback()
save()
setState(PObjectState)
...
PObjectState
commit(obj : PersistentObject)
delete(obj : PersistentObject)
rollback(obj : PersistentObject)
save(obj : PersistentObject)
OldDirty
State
commit(...)
delete(...)
rollback(...)
1
OldClean
State
delete(...)
save(...)
New
State
commit(...)
OldDelete
State
commit(...)
rollback(...)
Product
Specification
...
...
Sale
...
...
*
{ state.delete( this ) }
{
// default no-op
// bodies for
// each method
}
{ // rollback
{ // commit
PersistenceFacade.getInstance().update( obj )
obj.setState( OldCleanState.getInstance() ) }
{ state.rollback( this ) }
{ state.commit( this ) }
{ state.save( this ) }
Designing a Transaction
with the Command
Pattern
Ordering the database
tasks
Table A: caseNo
StudentNo
Health
Table B: StudentNo
StudentName
Inseart a record (“05001”,”wang”) to B
update A ("001","05001"),
Command
Context/Problem
How to handle requests or tasks that
need functions such as sorting
(prioritizing), queueing, delaying,
logging, or undoing?
Solution
Make each task a class that implements
a common interface
actions become objects, and thus can
be sorted, logged, queued, and so forth.
«interface»
ICommand
execute( )
undo()
DBInsertCommand
execute()
DBUpdateCommand
execute()
DBDeleteCommand
execute()
Transaction
commands : List
commit()
addDelete(obj:PersistentObject)
addInsert( obj:PersistentObject )
addUpdate( obj:PersistentObject )
sort()
...
1..*
DBCommand
object : PersistentObject
execute() {abstract}
undo() {leaf}
undo is a no-op fo
this example, but
more complex
solution adds a
polymorphic undo
to each subclass
which uniquely
knows how to und
an operation
PersistentObject
commit()
...
1
commands.add( new DBUpdateCommand (obj) );
use SortStrategy objects to allow
different sort algorithms to order the
Commands
perhaps simply
object.commit()
but each Command can
perform its own unique
actions
{
sort()
for each ICommand cmd
cmd.execute()
}
Lazy Materialization
with a Virtual Proxy
Manufacturer
Proxy
realSubject : IManufacturer
- getRealSubject() : IManufacturer
+ getAddress()
...
Manufacturer
address
getAddress()
...
«interface»
IManufacturer
getAddress()
...
Proxy-for 1
realSubject
{
return getRealSubject().getAddress()
}
ProductSpecification
manufacturer : IManufacturer
...
getManufacturerAddress() : Address
1
{
if ( realSubject == null )
realSubject = PersistenceFacade.get(oid, Manufacturer.class);
return realSubject;
}
PersistentObject
oid
...
1
{
return manufacturer.getAddress()
}
actually references an
instance of
ManufacturerProxy
1
2
3
// EAGER MATERIALIZATION OF MANUFACTURER
class ProductSpecificationRDBMapper
extends AbstractPersistenceMapper{
protected Object getObjectFromStorage( OID oid ){
ResultSet rs =
RDBOperations.getlnstance().getProductSpecificationData( oid );
ProductSpecification ps = new ProductSpecification();
ps.setPrice( rs.getDouble( "PRICE" ) );
// here's the essence of it
String manufacturerForeignKey = rs.getString( "MANU_OID" );
OID manuOID = new OID( manufacturerForeignKey );
ps.setManufacturer(
(Manufacturer) PersistenceFacade.getInstance(). get(manuOID,
Manufacturer.class) );
// or LAZY MATERIALIZATION OF MANUFACTURER
ps.setManufacturer( new ManufacturerProxy( manuOID ) );
the Representing Object
Relationships as Tables
one-to-one associations
 Place an OID foreign key in one or both
tables representing the objects in
relationship.
 Or, create an associative table that records
the OIDs of each object in relationship.
one-to-many associations, such as a
collection
many-to-many associations
 Create an associative table that records
the OIDs of each object in relationship.
Unresolved Issues
• dematerializing objects
 Briefly, the mappers must define putObjectToStorage.
methods.
 Dematerializing composition hierarchies requires collaboration
between multiple mappers and the maintenance of associative
tables (if an RDB is used).
• materialization and dematerialization of collections
• queries for groups of objects
• thorough transaction handling
• error handling when a database operation fails
• multiuser access and locking strategies
• security—controlling access to the database

More Related Content

Similar to DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt

2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia IT
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptJulie Iskander
 
PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemyInada Naoki
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
 
Create a Customized GMF DnD Framework
Create a Customized GMF DnD FrameworkCreate a Customized GMF DnD Framework
Create a Customized GMF DnD FrameworkKaniska Mandal
 
Wed 1630 greene_robert_color
Wed 1630 greene_robert_colorWed 1630 greene_robert_color
Wed 1630 greene_robert_colorDATAVERSITY
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptxrani marri
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An IntroductionNguyen Cao
 
Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFPierre-Yves Ricau
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtimeDneprCiklumEvents
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptDonald Sipe
 
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012Amazon Web Services
 

Similar to DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt (20)

2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
 
6976.ppt
6976.ppt6976.ppt
6976.ppt
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemy
 
Group111
Group111Group111
Group111
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
Create a Customized GMF DnD Framework
Create a Customized GMF DnD FrameworkCreate a Customized GMF DnD Framework
Create a Customized GMF DnD Framework
 
Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with Examples
 
Wed 1630 greene_robert_color
Wed 1630 greene_robert_colorWed 1630 greene_robert_color
Wed 1630 greene_robert_color
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An Introduction
 
Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SF
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtime
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
 
Gephi Toolkit Tutorial
Gephi Toolkit TutorialGephi Toolkit Tutorial
Gephi Toolkit Tutorial
 

Recently uploaded

ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 

Recently uploaded (20)

ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 

DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt

  • 2. The Problem: Persistent Objects persistent object  An object that can survive the process or thread that created it. A persistent object exists until it is explicitly deleted ProductDescription Storage Mechanisms and Persistent Objects  Object databases  Relational databases  others
  • 3. The Solution: A Persistence Service from a Persistence Framework The framework should provide functions such as:  store and retrieve objects in a persistent storage mechanism  commit and rollback transactions
  • 4. persistence framework  general-purpose, reusable, and extendable set of types that provides functionality to support persistent objects framework  A set of collaborating abstract and concrete classes that may be used as a template to solve a related family of problems. It is usually extended via subclassing for application-specific behavior
  • 5. Key Ideas Mapping Object identity Database mapper Materialization and dematerialization Caches Transaction state of object Transaction operations Lazy materialization Virtual proxies
  • 6. The Representing Objects as Tables pattern How do you map an object to a record or relational database schema? The Representing Objects as Tables pattern
  • 7. Manufacturer name city ... ... name city Now&Zen Mumbai MANUFACTURER TABLE : Manufacturer name = Now&Zen city = Mumbai Celestial Shortening San Ramon
  • 8. UML Data Modeling Profile «Table» ProductDescription «PK» OID : char(16) Description : varchar(100) ... «FK» Manu_OID : char(16) «Table» Manufacturer «PK» OID : char(16) Name : varchar(100) City : varchar(50) * 1 aggregate signifies a referential constraint: a ProductDescription row can't exist without a related Manufacturer row PK - primary key FK - foreign key
  • 9.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 19.
  • 20.
  • 22.
  • 23. object identifier (OID)pattern OID xyz123 abc345 This is a simplified design. In reality, the OID may be placed in a Proxy class. primary key Manufacturer city name oid : OID ... ... name city Now&Zen Mumbai MANUFACTURER TABLE : Manufacturer city = Mumbai name = Now&Zen oid = xyz123 Celestial Shortening San Ramon
  • 24. Accessing a Persistence Service with a Facade 1 PersistenceFacade ... getInstance() : PersistenceFacade get( OID, Class ) : Object put( OID, Object ) ... : DBProductsAdapter 1 : PersistenceFacade pd = get(...) // example use of the facade OID oid = new OID("XYZ123"); ProductDescription pd = (ProductDescription) PersistenceFacade.getInstance().get( oid, ProductDescription.class );
  • 25. Mapping Objects: Database Mapper or Database Broker Pattern Who should be responsible for materialization and dematerialization of objects (for example, a ProductDescription) from a persistent store?
  • 26. The PersistenceFacade—as true of all facades—does not do the work itself, but delegates requests to subsystem objects.  direct mapping  persistent object class itself  indirect mapping  Database Broker pattern  Database Mapper pattern
  • 27. Metadata-Based Mappers class PersistenceFacade { / / . . . public Object get( OID oid, Class persistenceClass ) { // an IMapper is keyed by the Class of the persistent object IMapper mapper = (IMapper) mappers.get( persistenceClass ); // delegate return mapper.get( oid ); } //... } usage: (Manufacturer) PersistenceFacade.getInstance(). get( manuOID, Manufacturer.class) );
  • 28. each mapper gets and puts objects in its own unique way , depending on the kind of data store and format 1 PersistenceFacade getInstance () : PersistenceFacade get ( OID , Class ) : Object put ( OID , Object ) ... ProductSpecification RDBMapper ... get ( OID ) : Object put ( OID , Object ) ... ProductSpecification FlatFileMapper ... get ( OID ) : Object put ( OID , Object ) ... Manufacturer RDBMapper ... get ( OID ) : Object put ( OID , Object ) ... note that the Class as a parameter is no longer needed in this version of get , as the class is "hardwired " for a particular persistent type 1 «interface» IMapper get (OID ) : Object put ( OID , Object ) ... Class UML notation : This is a qualified assocation . It means : 1. There is a 1-M association from PersistenceFacade to IMapper objects . 2. With a key of type Class , an IMapper is found (e.g., via a HashMap lookup )
  • 29.
  • 30. Template Method Pattern GUIComponent update() repaint() MyExcellentButton repaint() // this is the template method // its algorithm is the unvarying part public void update() { clearBackground(); // this is the hook method // it is the varying part repaint(); } hook method - varying part - overriden in subclass -may be abstract, or have a default implementation hook method overriden - fills in the varying part of the algorithm HOLLYWOOD PRINCIPLE: Don't call us, we'll call you Note that the MyExcellentButton--repaint method is called from the inherited superclass update method. This is typical in plugging into a framework class. FRAMEWORK class OUR class template method hook method
  • 31. Framework Design with the Template Method Pattern  if (object in cache)  return it  else  create the object from its representation in storage  save object in cache  return it
  • 32. Abstract PersistenceMapper + get ( OID ) : Object {leaf } # getObjectFromStorage (OID ) : Object {abstract } ... «interface» IMapper get (OID ) : Object put ( OID , Object ) ... // template method public final Object get ( OID oid ) { obj := cachedObjects .get (oid ); if (obj == null ) { // hook method obj = getObjectFromStorage ( oid ); cachedObjects .put ( oid , obj ); } return obj ; } HOOK TEMPLATE
  • 33. How to use the Framework
  • 34. ProductDescription RDBMapper # getObjectFromStorage(OID) : Object Abstract PersistenceMapper + get( OID) : Object {leaf} # getObjectFromStorage(OID) : Object {abstract} ... // template method public final Object get( OID oid ) { obj := cachedObjects.get(oid); if (obj == null ) { // hook method obj = getObjectFromStorage( oid ); cachedObjects.put( oid, obj ) } return obj } // hook method override protected Object getObjectFromStorage( OID oid ) { String key = oid.toString(); dbRec = SQL execution result of: "Select * from PROD_DESC where key =" + key ProductDescription pd = new ProductDescription(); pd.setOID( oid ); pd.setPrice( dbRec.getColumn("PRICE") ); pd.setItemID( dbRec.getColumn("ITEM_ID") ); pd.setDescrip( dbRec.getColumn("DESC") ); return pd; } IMapper
  • 35. Further factoring out the varying and unvarying parts of the algorithm.
  • 36.
  • 38. 1 «interface» IMapper get (OID ) : Object put ( OID , Object ) ... Class 1 + PersistenceFacade getInstance () : PersistenceFacade get ( OID , Class ) : Object put ( OID , Object ) ... Abstract PersistenceMapper + get ( OID ) : Object {leaf } # getObjectFromStorage (OID ) : Object ... Abstract RDBMapper + AbstractRDBMapper (tableName ) # getObjectFromStorage (OID ) : Object {leaf } # getObjectFromRecord (OID , DBRecord ) : Object - getDBRecord (OID ) : DBRecord Persistence NextGen Persistence ProductDescription RDBMapper + ProductDescriptionRDBMapper (tableName ) # getObjectFromRecord (OID , DBRecord ) : Object ProductDescription FileWithXMLMapper # getObjectFromStorage (OID ) : Object Sale RDBMapper ... # getObjectFromRecord (OID , DBRecord ) : Object ProductDescription InMemoryTestDataMapper # getObjectFromStorage (OID ) : Object
  • 39. Abstract PersistenceMapper + get( OID) : Object {leaf, guarded} ... // Java public final synchronized Object get( OID oid ) { ... } {guarded} means a "synchronized" method; that is, only 1 thread may execute at a time within the family of guarded methods of this object. IMapper
  • 40. Configuring Mappers class MapperFactory { public IMapper getProductSpecificationMapper(){...} public IMapper getSaleMapper() {...} }
  • 41. class MapperFactory{ public Map getAllMappers( ) {...} } class PersistenceFacade{ private java.util.Map mappers = MapperFactory.getlnstance( ).getAllMappers( ); }
  • 42. ProductDescription RDBMapper # getObjectFromStorage(OID) : Object Abstract PersistenceMapper + get( OID) : Object {leaf} # getObjectFromStorage(OID) : Object {abstract} ... // template method public final Object get( OID oid ) { obj := cachedObjects.get(oid); if (obj == null ) { // hook method obj = getObjectFromStorage( oid ); cachedObjects.put( oid, obj ) } return obj } // hook method override protected Object getObjectFromStorage( OID oid ) { String key = oid.toString(); dbRec = SQL execution result of: "Select * from PROD_DESC where key =" + key ProductDescription pd = new ProductDescription(); pd.setOID( oid ); pd.setPrice( dbRec.getColumn("PRICE") ); pd.setItemID( dbRec.getColumn("ITEM_ID") ); pd.setDescrip( dbRec.getColumn("DESC") ); return pd; } IMapper
  • 43. class ProductSpecificationRDBMapper extends …{ // hook method override protected Object getObjectFromStorage( OID oid ) { String key = oid.toString(); dbRec = SQL execution result of: "Select * from PROD_SPEC where key =" + key ProductSpecification ps = new ProductSpecification(); ps.setOID( oid ); ps.setPrice( dbRec.getColumn("PRICE") ); ps.setItemID( dbRec.getColumn("ITEM_ID") ); ps.setDescrip( dbRec.getColumn("DESC") ); return ps; } }
  • 44. class RDBOperations { public ResultSet getProductDescriptionData( OID oid ) {...} public ResultSet getSaleData( OID oid ) {...} ... } class ProductDescriptionRDBMapper extends AbstractPersistenceMapper{ protected Object getObjectFromStorage( OID oid ) { ResultSet rs = RDBOperations.getInstance().getProductDescriptionData( oid ); ProductDescription ps = new ProductDescription(); ps.setPrice( rs.getDouble( "PRICE" ) ); ps.setOID( oid ); return ps; }
  • 45.
  • 46. Pattern: Cache Management to maintain materialized objects in a local cache to improve performance (materialization is relatively slow) and support transaction management operations such as a commit. When objects are materialized, they are placed in the cache, with their OID as the key. Subsequent requests to the mapper for an object will cause the mapper to first search the cache, thus avoiding unnecessary materialization
  • 47. Transactional States and the State Pattern Persistent objects can be inserted, deleted, or modified. Operating on a persistent object (for example, modifying it) does not cause an immediate database update; rather, an explicit commit operation must be performed.
  • 48. OldClean OldDirty OldDelete commit / delete delete New [ from DB ] [new (not from DB )] save commit / update delete rollback / reload rollback / reload commit / insert State chart : PersistentObject Legend : New--newly created ; not in DB Old--retrieved from DB Clean --unmodified Dirty--modified Deleted
  • 50.
  • 51. GoF State pattern Context/Problem An object's behavior is dependent on its state, and its methods contain case logic reflecting conditional state-dependent actions. Is there an alternative to conditional logic? Solution Create state classes for each state, implementing a common interface. Delegate state-dependent operations from the context object to its current state object. Ensure the context object always points to a state object reflecting its current state.
  • 52.
  • 53. PersistentObject oid : OID state : PObjectState commit() delete() rollback() save() setState(PObjectState) ... PObjectState commit(obj : PersistentObject) delete(obj : PersistentObject) rollback(obj : PersistentObject) save(obj : PersistentObject) OldDirty State commit(...) delete(...) rollback(...) 1 OldClean State delete(...) save(...) New State commit(...) OldDelete State commit(...) rollback(...) Product Specification ... ... Sale ... ... * { state.delete( this ) } { // default no-op // bodies for // each method } { // rollback { // commit PersistenceFacade.getInstance().update( obj ) obj.setState( OldCleanState.getInstance() ) } { state.rollback( this ) } { state.commit( this ) } { state.save( this ) }
  • 54. Designing a Transaction with the Command Pattern
  • 55. Ordering the database tasks Table A: caseNo StudentNo Health Table B: StudentNo StudentName Inseart a record (“05001”,”wang”) to B update A ("001","05001"),
  • 56. Command Context/Problem How to handle requests or tasks that need functions such as sorting (prioritizing), queueing, delaying, logging, or undoing? Solution Make each task a class that implements a common interface
  • 57. actions become objects, and thus can be sorted, logged, queued, and so forth.
  • 58. «interface» ICommand execute( ) undo() DBInsertCommand execute() DBUpdateCommand execute() DBDeleteCommand execute() Transaction commands : List commit() addDelete(obj:PersistentObject) addInsert( obj:PersistentObject ) addUpdate( obj:PersistentObject ) sort() ... 1..* DBCommand object : PersistentObject execute() {abstract} undo() {leaf} undo is a no-op fo this example, but more complex solution adds a polymorphic undo to each subclass which uniquely knows how to und an operation PersistentObject commit() ... 1 commands.add( new DBUpdateCommand (obj) ); use SortStrategy objects to allow different sort algorithms to order the Commands perhaps simply object.commit() but each Command can perform its own unique actions { sort() for each ICommand cmd cmd.execute() }
  • 60. Manufacturer Proxy realSubject : IManufacturer - getRealSubject() : IManufacturer + getAddress() ... Manufacturer address getAddress() ... «interface» IManufacturer getAddress() ... Proxy-for 1 realSubject { return getRealSubject().getAddress() } ProductSpecification manufacturer : IManufacturer ... getManufacturerAddress() : Address 1 { if ( realSubject == null ) realSubject = PersistenceFacade.get(oid, Manufacturer.class); return realSubject; } PersistentObject oid ... 1 { return manufacturer.getAddress() } actually references an instance of ManufacturerProxy 1 2 3
  • 61. // EAGER MATERIALIZATION OF MANUFACTURER class ProductSpecificationRDBMapper extends AbstractPersistenceMapper{ protected Object getObjectFromStorage( OID oid ){ ResultSet rs = RDBOperations.getlnstance().getProductSpecificationData( oid ); ProductSpecification ps = new ProductSpecification(); ps.setPrice( rs.getDouble( "PRICE" ) ); // here's the essence of it String manufacturerForeignKey = rs.getString( "MANU_OID" ); OID manuOID = new OID( manufacturerForeignKey ); ps.setManufacturer( (Manufacturer) PersistenceFacade.getInstance(). get(manuOID, Manufacturer.class) ); // or LAZY MATERIALIZATION OF MANUFACTURER ps.setManufacturer( new ManufacturerProxy( manuOID ) );
  • 62. the Representing Object Relationships as Tables one-to-one associations  Place an OID foreign key in one or both tables representing the objects in relationship.  Or, create an associative table that records the OIDs of each object in relationship.
  • 63. one-to-many associations, such as a collection many-to-many associations  Create an associative table that records the OIDs of each object in relationship.
  • 64. Unresolved Issues • dematerializing objects  Briefly, the mappers must define putObjectToStorage. methods.  Dematerializing composition hierarchies requires collaboration between multiple mappers and the maintenance of associative tables (if an RDB is used). • materialization and dematerialization of collections • queries for groups of objects • thorough transaction handling • error handling when a database operation fails • multiuser access and locking strategies • security—controlling access to the database