Aliaspooryorik
ColdFusion ORM Book

Secondary Level Caching in ColdFusion ORM

I've been doing some performance improvements to a site by making use of the ORM Secondary Level Caching that is built into ColdFusion 9. Interacting with databases is a common bottleneck in applications so you want to reduce the amount of queries you need to run. ColdFusion has had the ability to cache queries for a long time by simply adding the cachedWithin attribute to cfquery. When you're using ORM, then there are similar in-built caching capabilites.

Firstly you need to enable the secondary level cache in your Application.cfc


this.ormSettings.secondaryCacheEnabled = true;

Once you've done that they you need to add the cacheuse attribute to the persistent CFCs (your entities) that you want to be cached. There are several values you could use, but the one I'm using is transactional.


component persistent="true" table="contents" cacheuse="transactional" cachename="content"
{
property name="id" column="content_id" generator="native";
}

The cachename attribute is optional, by default it will use the name of your entity.

Now when you use EntityLoadByPk to load a Content entity, then ColdFusion will automatically look in the cache first. If it finds it, it will use it, if it doesn't then it will query the database. As I've set the cacheuse value to "transactional" in my CFC, when I update (and persist) the entity, then the cache is updated for you so you don't need to worry about stale entries in the cache.

One of the great things about the ORM caching is the fine grained control is gives. One of the worst things about the ORM caching is the fine grained control is gives you! What do I mean? Well, consider the following:


a = EntityLoadByPK( "Content", 1 );
b = EntityLoad( "Content", 1, true );
c = EntityLoad( "Content", {id=1}, true );
d = EntityLoad( "Content", {id=1} ); // returns an array
e = ORMExecuteQuery( "from Content where id = :id", {id=1}, true );
f = ORMExecuteQuery( "from Content where id = :id", {id=1} ); // returns an array

They all get the content entity with an id of 1, but which ones would you expect to be pulled from the cache? The answer is that ORMExecuteQuery will not use the cache. This is not surprising as you could be using custom HQL but it does mean we have to do some extra work if we want to cache results from HQL:


e = ORMExecuteQuery(
    "from Content where id = :id",
    {id=1},
    true,
    {cacheable=true, cachename='content', timeout=60}
);

The above will cache the result with a key name of "content" for 60 seconds. If you update the entity within those 60 seconds, then you won't get the updated entity. This is similar to how it works with cached queries, but you need to be aware of it.

If you prefer to write your HQL in cfquery blocks (ColdFusion 9.0.1) then you'll need to use the new ormoptions attribute:


<cfset options = {cacheable=true, cachename='content', timeout=60}>
<cfquery name="q" dbtype="hql" ormoptions="#options#">
    from Content where id = <cfqueryparam value="1">
</cfquery>

<cfset e = q[1]>

10 comments

  1. So when you do use ORMExecuteQuery with a cache how do you ensure against stale records if you previously updated an entity?

    Comment by Joseph Swenson – July 12, 2011
  2. Simple explanation for such a complex topic. Well done.

    Comment by Aaron Greenlee – July 12, 2011
  3. Very nice explanation of secondary caching. It allowed me to see where I went wrong in an earlier attempt and how I can correct it. Thanks!

    Comment by Craig Kaminsky – July 12, 2011
  4. So just to clarify, your entityname is Content(S) but your cachename is content , so you query the cachename?

    Comment by Faisal Abid – July 13, 2011
  5. @Joseph, you can evict Evict content from secondary cache and ORM has a few functions to help you. Have a look at:
    adobe.ly/nZ8xyt

    I tend to not cache HQL results for very long. One hit on the database a minute is generally not going to cause a problem, so that means I don't have to worry in most cases about the data being out of sync for display purposes as at the most it will only be for 1 minute. Obviously, this will depend on what the data is and if it needs to be real-time.

    @Aaron - thanks!

    @Craig, from your blog it looks like you're working with Railo. Does it work the same?

    @Faisal, I'm not quite sure what you mean. My table name in the database is contents, but my Entity is Content. You don't query the cache as such, but ColdFusion will look for that key in cache.

    Comment by John Whish – July 13, 2011
  6. I never use the secondary cache of ORM and it look great. Just a question...

    If your entity CFC is called "Article.cfc" and the attribute "cachename" is "ArticleEntity" (in order to be different :P).
    To flush the cache of this specific entity, you can do:
    - ORMEvictEntity("Article") OR ORMEvictEntity("ArticleEntity") ?
    - ORMEvictCollection("Article", "ArticleEntity") ?
    - ORMEvictQueries("ArticleEntity") ?
    (the cachename attribute disturbs me ^^)

    Another...
    Is it possible to have a kind of report of what is cached, how many items, how many size, ... ? This question is not specific to ORM caching.
    For example, I have an application that use a lot of template caching and I would like to know how many bytes are saved in memory...
    For this moment I use cacheGetMetadata() to do a sum of their size but cacheGetMetadata() is very costly and mainly with a lot of different cached items.

    Comment by Loic Mahieu – July 13, 2011
  7. @Loic, you would use ORMEvictEntity("Article") to evict the all the Article entities in the cache, it uses the Entity name, not the cachename. If you just wanted to evict a specific article, then you can do ORMEvictEntity("Article",1).

    ORMEvictCollection is for relationships (such as one-to-many), ORMEvictQueries is for clearing out the cached HQL queries.

    As for reporting on the cache size, as far as I know then cacheGetMetadata is the only way of doing it. ColdFusion does use EHCache under the hood so you may be able to get some better metrics from there, but I'm afraid I don't know.

    Comment by John Whish – July 13, 2011
  8. @John Thanks for you details.
    But... I don't understand what is the goal of the "cachename" CFC attribute. :) Why is it there? Where can you use it ? Where is it used ?

    Comment by Loic Mahieu – July 13, 2011
  9. @Loic - that's a damn good question! I'll have to do some digging... :)

    Comment by John Whish – July 14, 2011
  10. @John / @Loic - cachename is so you can specify which cache the data should be stored in. This really comes into play when you create a custom ehcache.xml file with additional rules per named cache.

    For instance, you could say that for DailyCache (in ehcache.xml), all objects should be evicted after a period of inactivity of a day, and then for Article.cfc and for Author.cfc, you can specify DailyCache as the cachename, and they will share that cache and it's settings. There are many other ehcache settings than just cache expiration, but that was the simplest example :)

    Comment by Shannon Hicks – July 30, 2011

Leave a comment

If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Please note: If you haven't commented before, then your comments will be moderated before they are displayed.

Please subscribe me to any further comments
 

Search

Wish List

Found something helpful & want to say ’thanks‘? Then visit my Amazon Wish List :)

Categories

Recent Posts