Before starting on the advanced topics, I thought it will be better to build some ground and hence I decided to do a post on the ORM basics. In this post, we will build a simple example to get a taste of ColdFusion ORM (CF-ORM) and during that we will also understand some of the basic concepts.
ORM is object relational mapping and in ColdFusion, objects are created using CFC. CFCs that needs to be persisted are called persistent CFC and that is marked by setting ‘persistent’ attribute to true on the component. We also need to define what persistent fields will be there in a persistent CFC and that is defined using ‘cfproperty’. A field/property is marked persistent by setting persistent attribute to true on the cfproperty. By default, if the CFC is persistent, all its properties are considered as persistent unless you mark a property non-persistent. So typically ‘persistent’ attribute on the property is used only when you need to make that property non-persistent.
Each persistent CFC in ColdFusion application maps to a table in the database and each property in the persistent CFC maps to a column in the table (not exactly true but we will come to that later.. For the time being lets keep it that way). We will use the cfartgallery datasource for this example which has Artists and Art tables.
The first thing you need to do is – enable ORM for the application and define a datasource to be used (What is an ORM without a datasource?). ColdFusion ORM uses Application.cfc to define all the ORM specific settings. (If you haven’t started using Application.cfc for your application, its time to start using it!)
Application.cfc
Component { this.name="ArtGallery"; this.ormenabled="true"; this.datasource="cfartgallery"; }
Note that the datasource setting defined here makes it the default datasource of your application which can be used by tags like cfquery, cfinsert, cfupdate, cfdbinfo. The same default datasource will be used by ORM as well.
There are a whole bunch of ORM related configuration that you can do in application.cfc which you can refer here.
Now that the application is configured, let us build the object and define the persistence information on it. To start with, we will first define the Artist.cfc
Artists.cfc
/** * @persistent */ Component { property name="artistid" generator="increment"; property firstname; property lastname; property address; property city; property state; property postalcode; property email; property phone; property fax; property thepassword; }
This is the most simplistic definition of the component where we have defined only the component and its properties names. Since the table for this CFC already exists in the database, we have not added any table specific information in this and we will let ORM infer all the information from the database. The only additional setting that we have added here is the ‘generator’ attribute which is used to auto-generate the primary key.
After the components are defined, the first request to this application (i.e a page in this application) will make CF-ORM do all the setup necessary (basically generation of hibernate configuration, mapping files, building the session factory etc). Once the setup is done, you are all set to work with the entities.
We will first list all the artists and here is what you need to do for that
listAll.cfm
<cfscript> artists = EntityLoad("Artists"); writedump(artists); </cfscript>
To load a particular Artists with its ID, here is what you do
list.cfm
<cfscript> artist = EntityLoadByPK("Artists", 1); writedump(artist); </cfscript>
There are several flavors of EntityLoad functions details of which can be read here
Let us now see how to perform insert and update on it.
save.cfm
1 2 3 4 5 6 7 8 9 10 11 | <cfscript><br> // Insert a new artist artist = new Artists(); artist.setfirstname("Leonardo"); artist.setlastname("Da vinci"); artist.setcity("Paris"); EntitySave(artist); writeOutput(artist.getartistid());// Update an artist artist = EntityLoadByPK("Artists", 2); artist.setcity("NewYork"); // artist is automatically updated. </cfscript> |
As we see in the above example, EntitySave is used to insert/update an object in the table. There are some important things to note here
- EntitySave is an intelligent function which automatically finds if a new row needs to be inserted for the given object or whether an existing row needs to be updated.
- We called EntitySave for the insert here but not for update but even then artist ‘2′ gets updated. So how did that happen? Actually what happens here is when you load an artist object, it becomes associated with the hibernate session which keeps track of any changes in the object and automatically saves it when the session is flushed. We will talk about more about hibernate session in a later post. For the time being lets just say that Hibernate Session is a short-lived object that represents a conversation between the application and the persistence layer and also acts as the first level of cache.
- We did not write any setter or getter method for artist’s properties in Artists.cfc but we are calling them here. That works because ColdFusion 9 automatically generates accessor methods for any property written in a CFC. More details on generated methods in a later post.
- At line no 6, we called entitySave, but if you check the database, the row is not inserted yet. So when does that happen? Hibernate batches up all the operations till the end of the request or to be exact till hibernate session is flushed. ColdFusion ORM starts up a session when the first ORM method is called in the request and is automatically flushed when the request ends. The batching is done for performance reason so that hibernate executes the sql with the final state of the objects. It will be a huge performance bottleneck if ORM keeps executing sql for each changes in the object.
To delete an Artist, you need to call EntityDelete() passing the object to be deleted.
delete.cfm
<cfscript> artist = EntityLoadByPK("Artists", 15, true); EntityDelete(artist); </cfscript>
Relationship
So far we have seen how to perform CRUD for a single entity. But in any application, there will be entities which are associated and ORM must load the associated object as well when loading a particular entity. For our example, an Art will have an Artist and when loading the art object, it should also load the associated artist. So lets build the model first after which we will see how to work with the association.
In cfartgallery, the table Artists has a one-to-many relationship with Art table, which are joined using the foreign key column ARTISTSID. This means that each artist has created multiple arts and each art is created by one artist. To represent this in the object model, each ARTIST object would contain an array of ART objects. Each ART object will also contain a reference to its ARTIST object thereby forming a bidirectional relation.
To achieve this, we will need to add an extra property ‘arts’ to ‘Artists’ that contains an array of ART objects for that Artist. The modified Artists.cfc would look like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | /** * @persistent */ Component { property name="artistid" generator="increment"; property firstname; property lastname; property address; property city; property state; property postalcode; property email; property phone; property fax; property thepassword; property name="arts" fieldtype="one-to-many" fkcolumn="artistid" cfc="Art" cascade="all" inverse="true"; } |
Here is the Art.cfc
1 2 3 4 5 6 7 8 9 10 11 12 | /** * @persistent */ Component { property name="artid" generator="increment"; property artname; property price; property largeimage; property mediaid; property issold; property name="artist" fieldtype="many-to-one" fkcolumn="artistid" cfc="Artists" ; } |
Notice the artist property above which is of many-to-one type. Also notice that both the property use the same value for fkcolumn attribute i.e ‘artistid’ of Art table that references artistID pk of Artist table.
Since we have added a new persistent CFC (Art.cfc) after the application was loaded, we need to re-initialize the ORM for this application so that mappings for Art.cfc also gets generated. This can be done by calling ORMReload() method. There are some nice ways to do this but for the time being lets keep it simple by putting this in a separate page which we will call to reload ORM.
initializeORM.cfm
<cfset ormReload()>If you load and dump Artist (using listAll.cfm), you should also see the associated art objects for artists.
Now let us create a new Art and associate it with an existing Artist.
artCreate.cfm
1 2 3 4 5 6 7 8 9 10 | <cfscript> artist = EntityLoad("artists", 1 ,"true"); art = new Art(); art.setartname("landscape"); art.setPrice(1500); art.setissold(false); art.setartist(artist); artist.addArts(art); EntitySave(art); </cfscript> |
If you notice line 7-8 above, we associate artist to art by calling art.setArtist(artist) as well as art to artist by calling artist.addArts(art). Hibernate needs us to do this in order to set up the bidirectional relation properly. Since it is a bidirectional relation, you must also decide which side will set the relation in the database. i.e which side of the relation will set the fkcolumn in the table. This is controlled by the “inverse” attribute of proeprty, which if set to true, tells hibernate that this is a inverse of the other relation and this side of relation should be ignored for persistance. If you don’t set inverse to true, Hibernate will unnecessarily fire two sqls for the same association.
So there you have it. We have seen how you can use ORM to perform the basic CRUD operations on entities. For more details, you can refer to the ORM doc and Hibernate docs.

#1 by John Whish on July 17th, 2009
| Quote
Hi Rupesh, I noticed you’re using EntityLoadByPK in your code, I can’t see it in the CF9 docs. Am I right in thinking that EntityLoad(”artists”, 1 ,”true”) is the same as EntityLoadByPK(”artists”, 1)? Thanks.
#2 by Rupesh Kumar on July 17th, 2009
| Quote
I was waiting for someone to notice this
Yes, EntityLoad(”artists”, 1 ,”true”) is same as EntityLoadByPK(”artists”, 1)
This method was added because it always gives the object right back and you don’t have to pass the boolean parameter. however it was not documented because it was felt that people don’t need to know an extra method which does the exact same thing.
#3 by James Netherton on July 20th, 2009
| Quote
Haven’t reported this to Adobe but I ran into a weird problem testing the ORM stuff. I’m running Ubuntu 9.04 and have deployed CF 9 as a WAR under tomcat 6.
When calling EntityLoad I noticed the page execution would suddenly stop. Looked at the server logs and noticed lots of java.lang.NoClassDefFoundError: javax/transaction/Synchronization exceptions.
Had to manually add jta.jar into the lib directory. Looked inside the WAR file and jta.jar didn’t seem to be packaged, presumably it should be?
#4 by Rupesh Kumar on July 27th, 2009
| Quote
@James, we don’t package this because we assume that jta classes will be available on all the application servers we support.
Tomcat is not an application server and is just a servlet container. Hence it does not contain these classes. You would need to include jta.jar in the classpath as you did. Ant btw, ColdFusion does not officially support tomcat. So we have never tested ORM on tomcat.
#5 by Tony Nelson on August 3rd, 2009
| Quote
Is there any way to have Hibernate automatically trim the property values before saving to the database?
For example, if you had:
art = new Art();
art.setartname(” landscape “);
EntitySave(art);
it would insert just “landscape”?
Or if you had:
art = new Art();
art.setartname(”");
EntitySave(art);
It would insert NULL rather than an empty string?
#6 by Rupesh Kumar on August 3rd, 2009
| Quote
ORM respects whatever value you set in the object. ORM should not trim the values or it should not convert empty string to null blindly. Doing these sort of things can throw up lot of surprises in your application.
However there is definitely a way for you to do that in a central place for your entire application using event Handler. In the event handler, in preInsert and preUpdate methods, you can take check the values – you can trim it there and if it is empty string, you can set it to null.
#7 by Tony Nelson on August 4th, 2009
| Quote
That makes sense, although I was hoping there might be a way to set something like this.ormSettings.trimProperties = true.
I was able to trim all the values using a global event handler, but how would I set a value to null? Here’s what my preInsert looks like right now:
Does that look right? Is there a better way I could be writing it? Also, I’m a little worried about performance.
On a side note, it would be really nice to be able to do arguments.entity["set#property.name#"](trim(value)), but that’s a little wishful thinking
#8 by Tony Nelson on August 4th, 2009
| Quote
Looks like my code didnt’ come through. Let’s try that again…
<cffunction name="preInsert" access="public" returntype="void">
<cfargument name="entity" type="any" />
<cfset var properties = getMetaData(arguments.entity).properties />
<cfset var property = "" />
<cfset var value = "" />
<cfloop array="#properties#" index="property">
<cfinvoke component="#arguments.entity#" method="get#property.name#" returnvariable="value" />
<cfif !isNull(value)>
<cfinvoke component="#arguments.entity#" method="set#property.name#">
<cfinvokeargument name="1" value="#trim(value)#" />
</cfinvoke>
</cfif>
</cfloop>
</cffunction>
#9 by Rupesh Kumar on August 4th, 2009
| Quote
You know what, I think it is not a good idea to use event handler for this purpose. This will indeed be expensive. I think you should take care to trim/validate when you set the value on the object.
These kind of things should be done by the application and not the framework. So lets say, you get the input data from form, you can trim it right there and then set it on the object.
#10 by Tony Nelson on August 5th, 2009
| Quote
I agree, especially considering a lot of frameworks already combine the form/url scopes into a shared request context object, which could easily be trimmed.
Aside from that, is there any way to have Hibernate save empty strings as NULL rather than ”?
#11 by Rico Suave on August 18th, 2009
| Quote
I’m wondering why the object property-values are set with methods rather than with properties, so why not:
art.artname = “landscape”;
instead of:
art.setartname(”landscape”);
IMHO the former syntax makes more sense.
#12 by david buhler on August 18th, 2009
| Quote
I can’t actually get the child entity to populate with the query of the first entity. It did work, and then I changed something, and now the second entity is never shown.
I have a Person object.
I want to add an Address to the Person.
When I request people, I want to see each of their addresses.
Here’s my code:
Address.cfc
Person.cfc
SaveUser.cfm
person = new Person();
address = new Address();
address.setAddress_1(’address 1′);
address.setAddress_2(’address 2′);
address.setCity(’city name’);
address.setZip(12345);
//person.setAddress(address);
address.setPerson(person);
person.setEmail(’person@acme.com’);
person.setPassword(’catcat’);
EntitySave(person);
// — FLUSH
ORMFlush();
peopleList = EntityLoad(”person”);
#13 by david buhler on August 18th, 2009
| Quote
I posted the code complete at: http://snipt.org/lnoh
#14 by Rupesh Kumar on August 18th, 2009
| Quote
I don’t see any relationship definition here in these two cfc. So, this code would not have established the relation between Person and address in the database. Also, ORM will not have any way to load and associate the Address Object when you load Person.
You need to define the relationship metadata on the address property of Person and similarly on the person property of Address.
#15 by Darrin on October 13th, 2009
| Quote
I am having a issue with ORM, I have a user, and address table so a user can have many address’s. I can not get teh address to insert with a user id, I can not get any data at all in the address table.
here is my code:
component persistent=”true” output=”false”
{
property name=”IDUser” fieldtype=”id” generator=”native” type=”numeric” default=”0″ ormtype=”integer” notnull=”true”;
property name=”Name” ormtype=”string”;
property name=”Email” ormtype=”string” ;
property name=”Addresss” cfc=”address” fieldtype=”one-to-many” fkcolumn=”user” cascade=”all” inverse=”true”;
}
/**
* @persistent
*/
component
{
property name=”addressID” fieldtype=”id” generator=”native” type=”numeric” default=”0″ ormtype=”integer” notnull=”true”;
property string address1;
property string address2;
property string city;
property string state;
property string zip;
property name=”user” cfc=”user” fieldtype=”many-to-one” fkcolumn=”IDUser”;
}
// create a new user
User1 = EntityNew( “User” );
// set properties
User1.setName( ‘xxx’ );
User1.setEmail( ‘xxx@d.com’ );
EntitySave( User1, True );
writeOutput(User1.getIDUser());
Adddres1 = EntityNew( “address” );
Adddres1.setAddress1( “PSC 46″ );
Adddres1.setAddress2( “Box 146″ );
Adddres1.setCity( “APO” );
Adddres1.setState( “AE” );
Adddres1.setZip( “09456″ );
// save the new user
User1.addAddresss( Adddres1 );
EntitySave( Adddres1, true );
#16 by Rupesh Kumar on October 13th, 2009
| Quote
Hi Darrin,
I see couple of issues here.
1. In User.cfc, the fkcolumn value for the Address property should be “IDUser” which is the fkcolumn in Address table.
2. For relationship, You need to set the relationship properly. you need to set the user on address by calling User1.setAddress(address1) before calling entitysave on address1.
Alternatively you need to call EntitySave(User1) after calling user1.addAddress(address1)
#17 by Jim on February 19th, 2010
| Quote
How do you pass null values from a Flex VO that is bound to the Coldfusion ORM CFC? For instance if I have a numeric field in the database that has null values, I have no problem retrieving a row of data into a Coldfusion CFC then to Flex, even if the value for the numeric is null. But when I try passing a null value for that numeric back to Coldfusion, it ends up trying to save it as a “0″, which is not at all what I want. I tried setting required=”false” with no luck.
I also end up with validation errors on dates where type=”date” for the column property when I try passing a null or an empty string from Flex to Coldfusion, I need to be able to save a null for the date column. The same thing happens when I have validate=”email” for a column, it complains if I try passing a null value from Flex to the Coldfusion ORM CFC. Thanks for any help. For now I have written my own validation routine that can validate emails, dates, etc. and checks if there is an empty value for a property. But I have to set my dates to the “Any” data type to get around this.
Thanks for any help.
#18 by Rupesh Kumar on February 19th, 2010
| Quote
Jim,
This is something that came up recently and we are evaluating it currently. The validator in CF skips the validation if the property value is null. However when the object is coming over from flex to CF, the translation layer converts the null value to empty string (for string)or ‘0′ (for int). There is no way currently, to tell the translation layer to skip this conversion.
We would try to get this fixed ASAP, but until then, the only workaround is – In all the service methods that is called by flex, change these empty string or “0″ back to null using javacast.
#19 by Jim on February 19th, 2010
| Quote
Is it possible to use coldfusion mappings in the cfc attribute of cfproperty when defining relationships in a CFC ORM object? It doesn’t seem to be possible as I was getting errors until I used the full path from the web root, rather than using a Coldfusion mapping.
#20 by Rupesh Kumar on February 19th, 2010
| Quote
You can definitely use mappings in the cfc attribute of relationship. The mapping can be server level or application level. CF-ORM just needs the fully qualified cfc name and it uses the same resolution mechanism that is used by createObject. The only thing that you need to take care is that the CFC should have a unique fully qualified name. i.e you should not have two mappings in a way such that the same CFC can have two different fully qualified name.
If it is not working for you, could you please send me the sample CFC and mappings, so that I can take a look?
#21 by Jim on February 22nd, 2010
| Quote
Thanks so much for the replies. Now that I know the mappings are supported, let me play with it a little more to make sure all my code is correct.
I’ll just change those values back to null in my validate routine for now. I look foward to the fix, I’ll check the hot fixes periodically.
#22 by Jim on March 2nd, 2010
| Quote
The mapping seems to be working well now, but I have a couple of other questions that failed to be answered on the Adobe Coldfusion forum.
When you do and EntityLoad, it calls your init function on the CFC if you have one. All well and good, but is there a way to pass parameters to the init function?
Also, is there a way to include properties in your ORM class that are not included when binding to a Flex VO? I used remotingfetch=”false”, which works fine when you are passing the class back to Flex, but it does not work when you are trying to pass the Flex VO to Coldfusion. I also tried persistent=”false” on the Coldfusion CFC property, but no luck.
Thanks.
#23 by Rupesh Kumar on March 3rd, 2010
| Quote
Good to know that the mappings are working fine.
We have clearly documented that the init method of your persistent CFC should have either no arguments or all the arguments should be optional. ColdFusion will always call this method with no-arguments while calling EntityLoad. That is the standard that Hibernate follows that your java bean should have no-argument constructor.
Regarding your last question, if you don’t want the value to be peristed at all, then you can mark the property as non-persistent. However, I am curious to know why would you ever want it?
If you dont want that property to come to the CF side at all, then the only possible way is to have different named properties on the CF side and the flex side so that when the AS object gets converted to CFC, those values will not be set to any persistent property. however those values will then go under ‘THIS’ scope of the CFC.
#24 by Jim on March 3rd, 2010
| Quote
It wasn’t a question of whether or not I wanted it persisted (I do) but how to maintain data within the CFC that I did not want to pass back and forth to Flex. This might be items within the CFC that I want to keep track of that are not in the database, such as whether a value came in null from the database or not.
Thanks again for the reply.
#25 by BryonSR on March 9th, 2010
| Quote
Hello.
I have a similar issue to Jim’s, when testing the upgrade from CF8 to CF9 for our business environment. In one scenario, I pass a null array – as a property of an object – from Flex to CF, and the array gets converted to an empty string by the serialization process. This, of course, results in a type mismatch when I try to pass the object back to Flex.
It would be a pain to go through our code and add setters to everything, especially as they would have to accept “ANY” as a parameter to get around the empty string, which doesn’t feel like a good practice.
Any recommendations? Wait for a patch?