Jul 27, 2009

ColdFusion 9 and the ORM a simple example.

The ORM in ColdFusion 9 makes things easy. Now lets consider a website that has a section on the side displaying current news items
and lets say it always displays the last 2 most recent news items. As a query this would be:

This works great in Microsoft SQL server but what about MYSQL?

OK now I have 2 set's of code. More Database Support means more code but ColdFusion should = less code. Here is where the ORM can make this sort of thing a breeze:

So this 1 line of code :

can now replace:


Here is the code used for testing. With the ORM is simply a matter of creating an empty datasource with the database of your choice setting the dialect in Application.cfc and the ORM will even make the table for you you don't even need to load up Enterprise manager or phpmyadmin. I tested this on both MSSQL and MYSQL.
index.cfm
indexcfm
NewsItem.cfc
newsItemcfc
Application.cfc
applicationcfc - Copy

The final result:

d

Oh and here is the link to the excellent docs at Adobe

Also make sure if you write your own constructors to specify default values or the ORM will cause some errors about not passing in values when it creates the objects behinds the scenes.

5 comments:

  1. A note on setting the dialect. CF9 (through Hibernate) is supposed to be able to introspect the dialect of the datasource. So technically you don't need to set the dialect at all. However, I think it is a better practice to do it the way you have and specify it implicitly.

    I'm loving the ORM stuff so far. Now to get my hands on some Railo 3.2 goodness and have Hibernate support there as well.
    ReplyDelete
  2. Very nice post Paul. Keep em coming
    ReplyDelete
  3. Cool Example. I really like how you wrote NewsItem.cfc. Very slick.
    ReplyDelete
  4. Max rows would also have worked just fine instead of top or limit:

    lastTwoAsQuery = new Query();
    lastTwoAsQuery.setSql("select * from NewsItem order by id desc");
    lastTwoAsQuery.setMaxRows(2);
    writeDump(lastTwoAsQuery.execute());
    ReplyDelete
  5. Except that max rows is a performance inhibitor. Odly enough before this post I never used maxrows and was told over IM that maxrows was a good solution I accepted this till I read this: http://www.coldfusionjedi.com/index.cfm/2009/8/12/MAXROWS-Attribute--Not-as-good-as-I-thought
    ReplyDelete