ColdFusioning.com
My personal blog about ColdFusion, code, Google, & computers...
ColdFusioning: Pronunciation \kold-fy�-zhn-ing\ Noun: The action of one that writes ColdFusion.
Introduction to ColdFusion ORM
After coming back from MAX and seeing how wonderful ORM is, I had to jump right into it. I'm using ORM for the Tour de ColdFusion so I will post some code samples as I write them. The first set is an introduction to ColdFusion ORM.
The first thing you have to do is turn ORM on. You do this simply by adding the two following lines to your Application.cfc:
<cfset this.datasource = "yourDataSourceName" />
<cfset this.ormEnabled = true />
The DataSource name must match the one you created in the ColdFusion Administrator that is correctly pointed at a database. The next thing we'll do is define our table. We're going to call this one Categories.cfc:
<cfcomponent persistent="true">
<cfproperty name="CategoryID"
type="numeric"
validate="integer"
setter="false"
hint="I am the unique ID of the property."
persistent="true"
fieldtype="id"
column="categoryid"
ormtype="integer"
generator="identity"
length="10"
/>
<cfproperty
name="CategoryName">
<cfproperty
name="ParentID">
<cfproperty
name="theOrder">
<cfproperty
name="Deleted">
</cfcomponent>
This defines the Unique ID named as Category that auto-increments. We defined some other simple columns. Next we're going to insert some data into the database:
<cfscript>
newObj = EntityNew("Categories");
newObj.setCategoryName("UI Controls");
newObj.setParentid("2");
EntitySave(newObj);
writedump(newObj.getCategoryID());
ormflush();
</cfscript>
All this does is set the category name, parentid and saves it. It also retrieves the new CategoryID from the database. The last thing we're going to do is get some data back out of the database:
<cfscript>
categories = EntityLoad("categories", true);
writedump(categories);
</cfscript>
This is very similar to doing except ORM loads and array rather than a query:
<cfquery name="getCategories">
SELECT * FROM Categories
</cfquery>
<cfdump var="#getCategories#" />
Lastly, if you want to select a single record from the database you would use this code:
<cfscript>
categories = EntityLoad("categories", 5, true);
writedump(categories);
</cfscript>
With "5" being the CategoryID of the record you want to pull from the database.
ORM is truly a game-changer in the web development industry. It is going to enable ColdFusion developers to create applications even faster than we could before. I would recommend not waiting to learn it because it is only going to save you time in the long run.

There are no comments for this entry.
[Add Comment] [Subscribe to Comments]