coldfusion orm - part ii
TRANSCRIPT
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 1
ColdFusion-ORM - II
Rupesh Kumar
Sr. Computer Scientist
Blog: www.rupeshk.org
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 2
Agenda
Relationships (contd from last session)
Application settings
Advanced Mapping
What happens internally
Transaction & concurrency control
Caching & optimization
Event Handling
Q & A
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 3
Address.cfc
<cfproperty name="EmployeeObj" fieldtype="one-to-one" cfc="employees"
fkcolumn="EmployeeID">
Employees.cfc
<cfproperty name="addressObj" fieldtype="one-to-one" cfc="address"
mappedby="EmployeeObj">
3
Mapping One-to-One relationship
EMPLOYEES
EmployeeID(PK)
LastName
FirstName
Title
ADDRESSES
AddressID(PK)
HouseNumber
Street
City
State
Country
EmployeeID
1
1
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 4
EMPLOYEES
EmployeeID(PK)
LastName
FirstName
Title
Mapping Many-to-Many relationship
<cfproperty name=“Territories” fieldtype=“many-to-many” cfc=“territories”
linktable=“employeeterritories” fkcolumn=“EmployeeID”
inversejoincolumn=“TerritoryID”>
TERRITORIES
TerritoryID(PK)
TerritoryDescription
n n
EMPLOYEETERRITORIES
EmployeeID(PK)
TerritoryID(PK)
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 5
ColdFusion-ORM
APPLICATION
SETTINGS
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 6
Ormenabled – Specifies whether ORM should be used for the
ColdFusion application
Eg: <cfset this.ormenabled = true>
ORMSettings – The struct that defines all the ORM settings
Eg: <cfset this.ormsettings = {datasource=“employees”}>
datasource – Defines the default datasource for the
application.
Eg: <cfset this.datasource = “employees” >
66
Application Level Settings
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 7
cfclocation – Specifies the directory (or array of directories) to
search for persistent CFCs.
Eg: <cfset this.ormsettings = {cfclocation=“/empSys/model/”}>
savemapping – Specifies whether the generated Hibernate
mapping file has to be saved to disk.
Eg: <cfset this.ormsettings = {savemapping=“true”}>
logSQL – Specifies whether the SQL queries that are executed
by ORM will be logged.
Eg: <cfset this.ormsettings = {logSQL=“true”}>
77
Application Level Settings – ormsettings
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 8
datasource– Specifies the datasource to be used by ORM.
Eg: <cfset this.ormsettings = {datasource=“employees”}>
secondaryCacheEnabled – Specifies whether the secondary
cache will be enabled for ORM.
Eg: <cfset this.ormsettings = {secondarycacheEnabled=“true”}>
eventHandling – Specifies whether the event handling is
enabled for ORM.
Eg: <cfset this.ormsettings = {eventHandling=“true”}>
Many More…88
Application Level Settings – ormsettings
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 9
dbCreate – Specifies whether tables should be auto-generated at
application startup.
Update – create new or update if table exists
Dropcreate – drop and then create table
None* – do nothing
NamingStrategy – Specifies the method used to generate the
table/column names.
Default* – CFC names matches table/column name
Smart – CFC “OrderProduct” is “ORDER_PRODUCT” in db
Your own CFC – implements cfide.orm.INamingStrategy
SqlScript – Specifies the sql script file that will be run after the
tables are created. It can be used to initialize the DB.
99
Ormsettings for Auto-generating tables
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 10
Advanced Mapping
Collection Mapping
Embedded Mapping
Inheritance Mapping
Join Mapping
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 11
Collection Mapping
Similar to 1:n relationship
Useful when target table need not be mapped as persistent CFC
Just need information from the target table
Mapping defined similar to 1:n relationship
Demo
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 12
Embedded Mapping
One entity with multiple CFC
A cfproperty refers to another cfc
Mapping needs to be specified in *.hbm.xml
<hibernate-mapping>
<class name="cfc:Employees" entity-name="employee"
table="Employees">
<id name="ID" type="integer" column="EmployeeID">
<generator class="native"/>
</id>
<component name="Name" class="cfc:cname">
<property name="FirstName" type="string" column="FirstName"/>
<property name="LastName" type="string" column="LastName"/>
</component>
<property name="Title" type="string" column="Title"/>
<property name="BirthDate" type="date" column="BirthDate"/>
<property name="HireDate" type="date" column="HireDate"/>
</class>
</hibernate-mapping>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 13
Inheritance Mapping
Three Types
Table per hierarchy
Payment
+ID
+Amount
+Date
CreditCardPayme
nt
+CardNo
+CardType
ChequePayment
+ChequeNo
+bankName
+City
ID <<PK>>
Amount
Date
PaymentType
(discriminator)
CardNo
CardType
ChequeNo
BankName
City
Payment Table
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 14
Inheritance Mapping
Three Types
Table per hierarchy
Table per subclass without discriminator
Payment
+ID
+Amount
+Date
CreditCardPayme
nt
+CardNo
+CardType
ChequePayment
+ChequeNo
+bankName
+City
ID <<PK>>
Amount
Date
Payment Table
PaymentID
CardNo
CardType
CreidtCardPayment Table
PaymentId
ChequeNo
BankName
City
Cheque Payment Table
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 15
Inheritance Mapping
Three Types
Table per hierarchy
Table per subclass without discriminator
Table per subclass with discriminator
Payment
+ID
+Amount
+Date
CreditCardPayme
nt
+CardNo
+CardType
ChequePayment
+ChequeNo
+bankName
+City
ID <<PK>>
Amount
Date
PaymentType
(discriminator)
Payment Table
PaymentID
CardNo
CardType
CreidtCardPayment Table
PaymentId
ChequeNo
BankName
City
Cheque Payment Table
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 16
Join Mapping
Useful when using one CFC for multiple tables
<cfcomponent persistent="true“ table=“employee”>
<cfproperty name="id">
<cfproperty name="name">
<cfproperty name="city"
table="Address” joincolumn="addressId">
<cfproperty name="country"
table="Address“ joincolumn="addressId">
</cfcomponent>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 17
Application
Start
ORM
Enable
d?
Proceed
with other
activities
false
true
Create/Load
Hibernate
configuration if
specified
Load Hibernate
mapping files
(*.hbmxml)
Search for persistent
CFCs
Generate Hibernate
Mapping for
persistent CFCsDatabaseInspect
Generate DDL
based on dbcreate
Build Hibernate
Session Factory
Proceed
with other
activities
ORM Initialization
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 18
ORM Session
Represents a unit of work – typically a transaction
All the ORM operations happen in a session
Ensures a single instance of an entity.
Tracks changes made to the objects
SQLs are executed when session is flushed
Typically when the transaction is committed or when the request completes
Can use ORMFlush to force
Automatically managed by CF
In most cases, you don’t need to worry about it
Provides First Level Caching
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 19
ORM Session Management
New Request
New ORM Session
Call ORMFlush
Close Session
Batch all the operations
Application
Start
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 20
ORM Session Management – Transactions
20
New Request
New ORM Session
Application
Start
Call ORMFlush
Close ORM Session
New ORM Session
Call ORMFlush
Close ORM Session
Batch all the operations
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 21
Object States
Transient
Persistent
Detached
EntityNew()/ new()/
CreateObject
Transient Entity
Persistent Entities
EntitySave()
DB
Detached
Session ends
EntityLoad
ORMExecuteQuery
EnityMerge
EntityDelete
EntitySave
Session
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 22
Concurrency Control
Optimistic lock for high concurrency
Update only if the entity is not modified by other thread or externally.
optimisticlock attribute on cfc
All
All properties are included in where clause of update
Update myTbl set col1= newVal, col2= newVal2
where col1= oldVal and col2= oldVal2
Dirty
Includes only modified fields in the current session
Version (default)
Checks only version or timestamp column
<cfproperty name="lastModified“ fieldtype="timestamp|version“>
None
You can also choose the property for dirty check.
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 23
Fetching Strategy
Immediate fetching
Fetch target relationship in a separate SQL, immediately
<cfproperty name=“emp" fieldtype="one-to-many" cfc=“order"
fkcolumn=“EMPID“ lazy="false" fetch="select">
Lazy fetching
Default strategy, lazy=true
On demand, fetch related entities
Lazy = “extra” gets pk of orders and then all order columns from db
Eager fetching
Fetch together in a single SQL, fetch=“join”
Useful for 1:1 frequently used relationships
Batch fetching
When fetching relationship, get some more that maybe required later
Get Addr1 for emp101, plus address for emp102, 103 etc from the table depending on
batch size
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 24
Caching
Session Level
Ensures a single instance for a given ID
EntityLoad fetches data for the first time
Data is cached for the session
Next request in the same session will use cached data
EntyReload re-fetches
Secondary Level Cache
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 25
Secondary Level Cache
Caches data across sessions
In-memory/disk/clustered
Pluggable cache impls
Default - EHCache
Component Caching
Collection Caching
Query Caching
Secondary Cache
…
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 26
Secondary Level caching ...
Configuration in Application.cfc
ormsettings.secondarycacheenabled
ormsettings.Cacheprovider
JBossCache, OSCache, SwarmCache, Hashtable, DEFAULT - ehcache
ormsettings.cacheconfig
Appropriate config file for cache, e.g. ehcache.xml
In ORM cfc
“cacheuse” defines caching strategy
“cahcename” cache region, a bucket for this data
<cfcomponent persistent="true“
cachename=“foo_region" cacheuse="read-only">
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 27
Caching - examples
Component
<cfcomponent persistent="true“
cachename=“foo_region" cacheuse="read-only">
Relationship
Primary Key of the associated object is cached
The associated object itself is cached if coded as above
<cfproperty name="arts" fieldtype="one-to-many“
cachename="foo_region" cacheuse="read-write">
Query data
ORMExecuteQuery("from Art where issold=0", {}, false,
{cacheable=true, cachename=“foo_region"});
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 28
Caching – cacheuse
Read-only
Best performance for read only data
Nonrestrict-read-write
Use when data is updated occasionally
Read-write
Use if your data needs to be updated
More overhead than the two preceding strategies
Transactional
Transactional cache
Can only be used if the cache provider is transaction aware
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 29
Caching - cleanup
ORMEvictEntity
ORMEvictEntity("<component_name>", [primarykey])
ORMEvictCollection
ORMEvictCollection("<component_name>", "<relation_name>",
[primarykey])
ORMEvictQueries
ORMEvictQueries([cachename])
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 30
Event Handling
Set ormsettings.eventhandling=“true”
CFC level
preinsert and postinsert
predelete and postdelete
preupdate and postupdate
preload and postload
Application Level
Set ormsettings.eventhandler=“AppEventHandler.cfc”
Should implement the CFIDE.orm.IEventHandler interface
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential. 32
Thank You !
- http://www.rupeshk.org