ColdFusion 9 and ORM

Well as well all know by know that the news is ColdFusion 9 has stepped out into the wild, and that means we can all begin to have a play with some of the new features. And there is a lot that has been packaged into this release, and one of the biggest anticipated integrations into ColdFusion has to be Hibernate.

So lets have a quick look at how we can begin using Hibernate with ColdFusion 9.

One of the first things you will need to do is open up your Application.cfc and add the following code.

<cfset this.ormenabled = "true" />
<cfset this.datasource = "simpleDB" />
<cfset this.ormsettings = {dbcreate="update",dialect="MySQL", cfclocation="domain" } />

The first 2 lines in the above code is pretty straight forward, in that we are telling ColdFusion to enable the ORM and that we are going to be using the datasource simpleDB. Don't get this confused with not having to set it up in the Administrator, you will still need that.

The next line is the ormSettings and this has a number of properties, such as dbcreate is set to update. This means that the database will update when the component changes, other options are create and drop create. Where create will create the database and dropcreate will drop it then create the database. DropCreate is good for development, so that the database can be always pulled back to barebones setup again. In production you would always use update, the other two can have undesired effects so be very careful there.

Dialect is the type of database schema the ORM is going to be connected to, and is pretty straight forward.

Finally we have cfcLocation which tells the ORM that this is going to be the location relative to the Application.cfc, where it will look for the components that are going to be used.

So with that out of the way, what is a Domain Class or ORM Component going to look like.

component persistent="true" {
   property name="username" generator="assigned" fieldtype="id" datatype="string" unique="true";
   property name="firstName" datatype="string";
   property name="lastName" datatype="string";
   property name="password" datatype="string";
}

As you can see this is now using the new cfscript syntax, and it very straight forward, we are telling the component that we want to be persisted and we have 4 properties, one of which will be our unique primary key.

And that's pretty much the basics of an ORM, and to use it in a template or another component we will now call it like the following.

userAccount = new userAccount();

And we now have an object that is mapped to our database. In my next post I will go into some benefits of using ORM that is not easy to achieve with a normal ColdFusion cfquery.