ORM is Fun, Easy, Smells Great, and is Full of Beautiful Unicorns!
WHO AM I? 
• Luis Majano - Computer Engineer 
• Born in El Salvador ------------------> 
• Architecture + Software Design 
• CEO of Ortus Solutions 
• Adobe Community Professional 
• Creator of all things Box: 
ColdBox, ContentBox, WireBox....
AGENDA 
• Thought experiment 
• Silver Bullet 
• Advice from Special Guest 
• ColdBox ORM Services
Thought experiment? 
CF ORM was 
easy to use? 
OO way to 
query 
ORM was fast 
90% of biz 
reqs done 
Extensible 
way to finish 
the remaining 
10% 
Ich Brauche ein 
Weißbier! 
Compose my 
relationships
CONCLUSIONS 
• Can’t or doesn’t exist 
• Sounds like BS 
• What’s this latino up to? Is he trying to get my money 
PROVE IT!
ORM is NOT a silver bullet 
• Just another tool 
• Times you need the power of the database 
• Mix and match 
• What if you wanted array of structs, or lists or queries or arrays of data? 
• There is a learning curve, but it is worth the investment
Applied Benefits 
• Increase in productivity of about 40% 
• Rich Object Models 
• Deliver DB patching updates 
• Increased Flexibility 
• Great for abstracting vendor specific 
intricacies 
• OO Queries 
• Avg JDBC <10ms
Guru ORMpitka 
10 keys to ORM Success!
#1: OO Modeling is Key 
• ORM relationship modeling is key 
• OO is required 
• UML is your best friend 
• STOP THINKING ABOUT DATA 
• YOU ARE NOT MODELING A DATABASE
#2: Engine Defaults Not Great! 
• Do not use the CF engine defaults: 
• FlushAtRequestEnd = Send to Database 
• Session Management = Transactions 
• Lazy 
• Cascade 
• Caching
#3: Understand Hibernate Session 
• Not the same as session scope 
• A transitionary space 
• entityLoad() 
• entityNew() ? 
• A caching layer 
• You need to control when to send to DB 
• You can remove entities from it and clear it 
• You can attach a secondary cache to it
#4: Transaction Demarcation 
• Transactions demarcate SQL boundaries 
• Important for ORM and SQL 
• No communication to DB should occur without one 
• Must have reactive programming, expect the worst 
• Transaction Theory: 
• Any existing ORM session is flushed and closed 
• A new ORM session is created 
• Data can be committed or rollback 
• ORMFlush() does not work in a transaction block 
• If commit, then flushed to database
#5: Lazy Loading is KEY 
• You will fail if you do not use this! 
• Performance will SUCK! 
• Always Use It! 
• Lazy Types: 
• True = Only when you call getXX (all types) 
• Extra = Loads proxy objects with primary keys only (o-2m,m-2-m) 
• Proxy = Loads proxy object with primary key only (o-2-o, m-2-o) 
• fetch=“join” 
• Uses a single SQL query, great for performance 
• batchsize 
• For performance, like pagination for objects
#6: Avoid bi-directional 
• They can be more of a headache 
• Cascading Deletes 
• Inverse 
• Does it make sense? 
• Supporting methods for bi-directional linkage 
• Supporting methods for un-linkages
#6: Avoid bi-directional
#6: Avoid bi-directional
#7: Do not store entities in scopes 
• Don’t do it! 
• No linkage to Hibernate Session 
• Relationships will fail if not lazy 
• entityMerge() 
• Store ID’s instead
#8: Use DB Indexes 
• #1 Performance Problem 
• Identify relationships 
• Identify HQL, SQL 
• Learn them 
• property name=“isActive” index=“idxActive”
#9: Cache = BOOST! 
• Don’t go cache crazy 
• Develop a strategy 
• Does not store CFC, stores individual property values 
• Use distributed caches: ehcache, couchbase 
• You can cache: 
• Entity property data : Only caches properties data values 
• Entity association data : Only caches primary keys 
• Query data : HQL, ORMExecuteQuery() 
• Evictions: 
• ORMEvictEntity(), ORMEvictCollection()
#10: OO Modeling is Key 
• ORM relationship modeling is key 
• OO is required 
• UML is your best friend 
• STOP THINKING ABOUT DATA 
• YOU ARE NOT MODELING A DATABASE
ORM Extensions
ORM Extensions 
Base ORM Service 
Virtual ORM Service 
Active Entity 
Entity Populators 
Validation 
Event Handlers
Base ORM Service 
• Service layer for any entity 
• OO Querying, caching, transactions 
• Dynamic finders, getters, counters 
• Object metadata & session management 
• Exposes more features from Hibernate 
• 90% Foundation
Virtual/Concrete ORM 
• Extends Base ORM Services 
• Roots itself to a single entity = 
Less Typing 
• You can build the 10% 
Services
• Active Record Pattern 
• Sweet validation integration 
• DI Available 
Active Entity
• Populate Entities: xml, json, queries, structs 
• Compose relationships from simple values 
• Null support 
• Exclude/include fields 
• Server side validation 
• Dependency Injection Listeners 
• Custom Event Driven Programming 
Entity Populators 
Validation 
Event Handlers 
ORM Utilities
ORM Services in Action 
More awesome than a dinosaur riding a shark with a laser! 
box install cartracker-demo
Base ORM Service 
• count(), countWhere() 
• delete(), deleteAll(), deleteByID(), deleteByQuery(), delete Where() 
• evict(), evictEntity(), evictQueries() 
• executeQuery(), list() 
• exists() 
• findAll(), findAllWhere(), findByExample(), findIt(), findWhere() 
• get(), getAll(), 
• getKey(), getPropertyNames(), getSessionStatistics(), getTableName() 
• clear(), merge(), new(), refresh() 
• populate(), populateFromJSON(), populateFromXML(), populateFromQuery() 
• save(), saveAll()
Base ORM Service 
Dynamic Finders/Counters 
• Expressive Programming 
• Three types of dynamic Finders/Counters 
• findBy : find ONE entity 
• findAllBy : find ALL entities 
• countBy: Give you a count
Base ORM Service 
Dynamic Finders/Counters 
• Method Expressions 
• Conditionals 
• LessThanEquals, LessThan 
• GreaterThanEquals, GreaterThan 
• Like 
• Equal, NotEqual 
• isNull, isNotNull 
• Between, NotBetween 
• inList, notInList 
• Operators 
• And 
• Or 
• Query Options 
• ignoreCase, timeout, max, offset 
• cacheable, cachename
Criteria Builder 
Awesome OO Queries
Criteria Builder 
• Limitations of CF ORM: 
• entityLoad() has limited features 
• Some operations we always need an entity = slow 
• What if I want arrays, or arrays of structs 
• Complex relationships are hard to query 
• SQL/HQL string build is so 90’s == NOT FUN!
Criteria Builder 
• Programmatic DSL Builder 
• Rich set of criterias 
• Projections and Result transformations 
• Subqueries 
• Caching 
• SQL Inspections & Debugging
Criteria Builder
Criteria Builder 
• Request new criteria 
• newCriteria() 
• Add simple restriction(s) 
• Find all cars sold between April and July 
• Use between() 
• Get results 
• Use list( max, offset, timeout, sortOrder, ignoreCase, asQuery ) 
• Get counts 
• Use count()
Criteria Builder 
Restrictions 
• between() 
• eq() 
• gt() 
• ge() 
• gtProperty() 
• isEmpty() 
• isNull() 
• ne() 
• ilike() 
• and() 
• or() 
• not() 
• conjunction() 
• disjunction() 
• isTrue() 
• isFalse() 
• sqlRestriction() 
• ...much more!
Criteria Builder 
Retrievals 
• Retrieval 
• firstResult() 
• get() 
• list() 
• count() 
• Options 
• fetchSize() 
• readOnly() 
• maxResults() 
• cache(), cacheRegion() 
• timeout() 
• order()
Criteria Builder 
Aliases -> Joins 
• Allows you to do queries within 
relationships 
• Creates SQL Joins 
• Aliases can be nested, so if your entity 
knows about it, you can query it!
Criteria Builder 
Projections 
• Projects change nature of results 
• Arrays of data, or arrays of structs (Mighty Fast) 
• Once its added its there forever 
• avg 
• count 
• countDistinct 
• distinct 
• groupProperty 
• max 
• min 
• property 
• sum 
• rowCount 
• id 
• sqlProjection 
• sqlGroupProjection 
• detachedSQLProjection
Criteria Builder 
Debugging + Logging 
• Application.cfc 
• ormsettings.logsql = Never in production 
• Criteria Builder SQL Inspector 
• startSQLLog( returnExecutableSQL, formatSQL ) 
• stopSQLLog() 
• getSQLLog() 
• getSQL( returnExecutableSQL, formatSQL )
Q & A 
Thanks!

ORM Pink Unicorns

  • 1.
    ORM is Fun,Easy, Smells Great, and is Full of Beautiful Unicorns!
  • 2.
    WHO AM I? • Luis Majano - Computer Engineer • Born in El Salvador ------------------> • Architecture + Software Design • CEO of Ortus Solutions • Adobe Community Professional • Creator of all things Box: ColdBox, ContentBox, WireBox....
  • 3.
    AGENDA • Thoughtexperiment • Silver Bullet • Advice from Special Guest • ColdBox ORM Services
  • 4.
    Thought experiment? CFORM was easy to use? OO way to query ORM was fast 90% of biz reqs done Extensible way to finish the remaining 10% Ich Brauche ein Weißbier! Compose my relationships
  • 5.
    CONCLUSIONS • Can’tor doesn’t exist • Sounds like BS • What’s this latino up to? Is he trying to get my money PROVE IT!
  • 6.
    ORM is NOTa silver bullet • Just another tool • Times you need the power of the database • Mix and match • What if you wanted array of structs, or lists or queries or arrays of data? • There is a learning curve, but it is worth the investment
  • 7.
    Applied Benefits •Increase in productivity of about 40% • Rich Object Models • Deliver DB patching updates • Increased Flexibility • Great for abstracting vendor specific intricacies • OO Queries • Avg JDBC <10ms
  • 8.
    Guru ORMpitka 10keys to ORM Success!
  • 9.
    #1: OO Modelingis Key • ORM relationship modeling is key • OO is required • UML is your best friend • STOP THINKING ABOUT DATA • YOU ARE NOT MODELING A DATABASE
  • 10.
    #2: Engine DefaultsNot Great! • Do not use the CF engine defaults: • FlushAtRequestEnd = Send to Database • Session Management = Transactions • Lazy • Cascade • Caching
  • 11.
    #3: Understand HibernateSession • Not the same as session scope • A transitionary space • entityLoad() • entityNew() ? • A caching layer • You need to control when to send to DB • You can remove entities from it and clear it • You can attach a secondary cache to it
  • 12.
    #4: Transaction Demarcation • Transactions demarcate SQL boundaries • Important for ORM and SQL • No communication to DB should occur without one • Must have reactive programming, expect the worst • Transaction Theory: • Any existing ORM session is flushed and closed • A new ORM session is created • Data can be committed or rollback • ORMFlush() does not work in a transaction block • If commit, then flushed to database
  • 13.
    #5: Lazy Loadingis KEY • You will fail if you do not use this! • Performance will SUCK! • Always Use It! • Lazy Types: • True = Only when you call getXX (all types) • Extra = Loads proxy objects with primary keys only (o-2m,m-2-m) • Proxy = Loads proxy object with primary key only (o-2-o, m-2-o) • fetch=“join” • Uses a single SQL query, great for performance • batchsize • For performance, like pagination for objects
  • 14.
    #6: Avoid bi-directional • They can be more of a headache • Cascading Deletes • Inverse • Does it make sense? • Supporting methods for bi-directional linkage • Supporting methods for un-linkages
  • 15.
  • 16.
  • 17.
    #7: Do notstore entities in scopes • Don’t do it! • No linkage to Hibernate Session • Relationships will fail if not lazy • entityMerge() • Store ID’s instead
  • 18.
    #8: Use DBIndexes • #1 Performance Problem • Identify relationships • Identify HQL, SQL • Learn them • property name=“isActive” index=“idxActive”
  • 19.
    #9: Cache =BOOST! • Don’t go cache crazy • Develop a strategy • Does not store CFC, stores individual property values • Use distributed caches: ehcache, couchbase • You can cache: • Entity property data : Only caches properties data values • Entity association data : Only caches primary keys • Query data : HQL, ORMExecuteQuery() • Evictions: • ORMEvictEntity(), ORMEvictCollection()
  • 20.
    #10: OO Modelingis Key • ORM relationship modeling is key • OO is required • UML is your best friend • STOP THINKING ABOUT DATA • YOU ARE NOT MODELING A DATABASE
  • 21.
  • 22.
    ORM Extensions BaseORM Service Virtual ORM Service Active Entity Entity Populators Validation Event Handlers
  • 23.
    Base ORM Service • Service layer for any entity • OO Querying, caching, transactions • Dynamic finders, getters, counters • Object metadata & session management • Exposes more features from Hibernate • 90% Foundation
  • 24.
    Virtual/Concrete ORM •Extends Base ORM Services • Roots itself to a single entity = Less Typing • You can build the 10% Services
  • 25.
    • Active RecordPattern • Sweet validation integration • DI Available Active Entity
  • 26.
    • Populate Entities:xml, json, queries, structs • Compose relationships from simple values • Null support • Exclude/include fields • Server side validation • Dependency Injection Listeners • Custom Event Driven Programming Entity Populators Validation Event Handlers ORM Utilities
  • 27.
    ORM Services inAction More awesome than a dinosaur riding a shark with a laser! box install cartracker-demo
  • 28.
    Base ORM Service • count(), countWhere() • delete(), deleteAll(), deleteByID(), deleteByQuery(), delete Where() • evict(), evictEntity(), evictQueries() • executeQuery(), list() • exists() • findAll(), findAllWhere(), findByExample(), findIt(), findWhere() • get(), getAll(), • getKey(), getPropertyNames(), getSessionStatistics(), getTableName() • clear(), merge(), new(), refresh() • populate(), populateFromJSON(), populateFromXML(), populateFromQuery() • save(), saveAll()
  • 29.
    Base ORM Service Dynamic Finders/Counters • Expressive Programming • Three types of dynamic Finders/Counters • findBy : find ONE entity • findAllBy : find ALL entities • countBy: Give you a count
  • 30.
    Base ORM Service Dynamic Finders/Counters • Method Expressions • Conditionals • LessThanEquals, LessThan • GreaterThanEquals, GreaterThan • Like • Equal, NotEqual • isNull, isNotNull • Between, NotBetween • inList, notInList • Operators • And • Or • Query Options • ignoreCase, timeout, max, offset • cacheable, cachename
  • 31.
  • 32.
    Criteria Builder •Limitations of CF ORM: • entityLoad() has limited features • Some operations we always need an entity = slow • What if I want arrays, or arrays of structs • Complex relationships are hard to query • SQL/HQL string build is so 90’s == NOT FUN!
  • 33.
    Criteria Builder •Programmatic DSL Builder • Rich set of criterias • Projections and Result transformations • Subqueries • Caching • SQL Inspections & Debugging
  • 34.
  • 35.
    Criteria Builder •Request new criteria • newCriteria() • Add simple restriction(s) • Find all cars sold between April and July • Use between() • Get results • Use list( max, offset, timeout, sortOrder, ignoreCase, asQuery ) • Get counts • Use count()
  • 36.
    Criteria Builder Restrictions • between() • eq() • gt() • ge() • gtProperty() • isEmpty() • isNull() • ne() • ilike() • and() • or() • not() • conjunction() • disjunction() • isTrue() • isFalse() • sqlRestriction() • ...much more!
  • 37.
    Criteria Builder Retrievals • Retrieval • firstResult() • get() • list() • count() • Options • fetchSize() • readOnly() • maxResults() • cache(), cacheRegion() • timeout() • order()
  • 38.
    Criteria Builder Aliases-> Joins • Allows you to do queries within relationships • Creates SQL Joins • Aliases can be nested, so if your entity knows about it, you can query it!
  • 39.
    Criteria Builder Projections • Projects change nature of results • Arrays of data, or arrays of structs (Mighty Fast) • Once its added its there forever • avg • count • countDistinct • distinct • groupProperty • max • min • property • sum • rowCount • id • sqlProjection • sqlGroupProjection • detachedSQLProjection
  • 40.
    Criteria Builder Debugging+ Logging • Application.cfc • ormsettings.logsql = Never in production • Criteria Builder SQL Inspector • startSQLLog( returnExecutableSQL, formatSQL ) • stopSQLLog() • getSQLLog() • getSQL( returnExecutableSQL, formatSQL )
  • 41.
    Q & A Thanks!