<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Eric Fickes &#187; coldfusion9</title>
	<atom:link href="http://ericfickes.com/tag/coldfusion9/feed/" rel="self" type="application/rss+xml" />
	<link>http://ericfickes.com</link>
	<description>Design minded Internet Programmer</description>
	<lastBuildDate>Fri, 28 Oct 2011 04:14:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>I wonder if using Coldfusion9&#8242;s ORM would make this easier?</title>
		<link>http://ericfickes.com/2009/12/i-wonder-if-using-coldfusion9s-orm-would-make-this-easier/</link>
		<comments>http://ericfickes.com/2009/12/i-wonder-if-using-coldfusion9s-orm-would-make-this-easier/#comments</comments>
		<pubDate>Fri, 01 Jan 2010 02:50:09 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[adobe]]></category>
		<category><![CDATA[coldfusion]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[coldfusion9]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[structure]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=979</guid>
		<description><![CDATA[Rolling my own SQL solution Recently I was working on a medical website and was tasked with building a doctor directory page that had to pull data from three related tables.  For the viewers at home, here is a simplified &#8230; <a href="http://ericfickes.com/2009/12/i-wonder-if-using-coldfusion9s-orm-would-make-this-easier/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h2>Rolling my own SQL solution</h2>
<p>Recently I was working on a medical website and was tasked with building a <a href="http://sgpn.org/physicians.cfm" target="_blank">doctor directory page</a> that had to pull data from three related tables.  For the viewers at home, here is a simplified view of my tables.</p>
<div id="attachment_981" class="wp-caption aligncenter" style="width: 361px"><a href="http://ericfickes.com/wp-content/uploads/2009/12/doctor-practice-locations.png" rel="lightbox[979]"><img class="size-full wp-image-981" title="doctor-practice-locations" src="http://ericfickes.com/wp-content/uploads/2009/12/doctor-practice-locations.png" alt="Database tables : Doctors, Practices, and Locations" width="351" height="296" /></a><p class="wp-caption-text">Doctors, Practices, and Locations oh my</p></div>
<p>The first version of the page was easy to whip up because we were only showing primary location address which lives in the practices table.  ( NOTE : The diagram above was dumbed down to support this post ).  When the request came in to show all locations for each doctor&#8217;s practice, that&#8217;s when I had to put on my wizard hat and get tricky.</p>
<p>After some thinking I came up with two options for adding all locations for each doctor row :</p>
<ol>
<li>Build a second locations query for each doctor in the first query, then use code to merge the data together</li>
<li>Update the first query to include all necessary data, then use code to merge the data into a loopable structure</li>
</ol>
<p>Being a SQL junky, I decided to take the second route so I&#8217;m still only hitting the database once.  In the first version of this page, we always had one row per doctor and didn&#8217;t have to do any post processing of the data prior to sending to the page.  However, when the locations table gets added to our sql query, all of the doctor data gets duplicated for each location they are associated with, making the dataset look like this.</p>
<div id="attachment_984" class="wp-caption aligncenter" style="width: 474px"><a href="http://ericfickes.com/wp-content/uploads/2009/12/doctor-query.png" rel="lightbox[979]"><img class="size-full wp-image-984" title="doctor-query" src="http://ericfickes.com/wp-content/uploads/2009/12/doctor-query.png" alt="doctors, practice, and locations all in a single query" width="464" height="216" /></a><p class="wp-caption-text">When joining the third table, the first two get duplicated</p></div>
<p>Now that we&#8217;ve got all the data, you&#8217;ll notice that the doctor information gets duplicated.  This is where I built a cffunction to convert this query into a structure of individual doctors, each having an array of locations.  I used the doctor&#8217;s full name and id as the structure keys.  Great, now I can just loop through my new structure of doctors, then loop through each doctor.location array to draw the updated html table.  That is the goal here, but we&#8217;re not ready just yet.</p>
<p>If you&#8217;ve ever tried to <a title="cfloop: looping over a COM collection or structure" href="http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-71a6.html" target="_blank">loop over a Structure in Coldfusion</a>, you&#8217;ve probably noticed controlling the order of your data coming back can be tricky.  Here&#8217;s an example of what I&#8217;m talking about when looping through a structure.</p>
<div id="attachment_987" class="wp-caption aligncenter" style="width: 383px"><a href="http://ericfickes.com/wp-content/uploads/2009/12/simple-struct-loop.png" rel="lightbox[979]"><img class="size-full wp-image-987" title="simple-struct-loop" src="http://ericfickes.com/wp-content/uploads/2009/12/simple-struct-loop.png" alt="Looping through CF Structures, doesn't always loop in the order you'd expect" width="373" height="184" /></a><p class="wp-caption-text">Looping through a coldfusion structure can be a challenge</p></div>
<p>To get around this random order of looping through a structure, I did two steps prior to building the updated html table.</p>
<pre class="brush: coldfusion; title: ; notranslate">
	// UPDATE : extract key list ( DR full names ) so
	// you can sort the physicians my last name
	dr_list = StructKeyList( providers_struct );
	dr_list = ListSort( dr_list, &quot;textnocase&quot; );
</pre>
<p>This gives me an alphabetized list of all doctors inside my structure, which I convert to an array then loop through.  I know have a sorted loop that can pick all necessary doctor data out of my structure on command.  This solution took a little bit of time to figure, but wasn&#8217;t too bad.  After thinking about all the work needed to make this update, I wondered if using Coldfusion9&#8242;s Hibernate ORM would have made this update any easier.</p>
<h2>Porting SQL to ORM</h2>
<p>The first step in setting up  <a title="ColdFusion 9 has Hibernate built right in!" href="http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSD628ADC4-A5F7-4079-99E0-FD725BE9B4BD.html" target="_blank">Coldfusion9&#8242;s ORM</a> for this code is to enable the ORM in the application.</p>
<p>At the top of my Application.cfc I added the following lines.</p>
<pre class="brush: coldfusion; title: ; notranslate">
	&lt;cfscript&gt;
		// enable ORM
		this.ormenabled = true;

		// my datasource name, setup in the CFAdmin
		this.datasource = &quot;mysql-test&quot;;

		// the folder in my app where the cfc mapping files are location
		this.ormsettings.cfclocation = &quot;mappings&quot;;

		// this wasn't setup automatically for me
		this.ormsettings.dialect = &quot;MySQL&quot;;
	&lt;/cfscript&gt;
</pre>
<p>If you haven&#8217;t setup ORM in your Coldfusion9 application before, be sure to bookmark <a title="How do I configure ORM in Coldfusion9" href="http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSED380324-6CBE-47cb-9E5E-26B66ACA9E81.html" target="_blank">this livedoc page on configuring ORM</a>.  It will give you all the lowdown on all the fancy ORM bells and whistles.</p>
<p>After ORM is enabled, it was time to create my Hibernate mapping files for each of the database tables involved in this code.  For convenience sake, I went the CFC route, and only mapped the columns required for this example.  There are a number of ways to <a title="Define ORM mapping in Coldfusion9" href="http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WS53C28604-E798-4175-97AE-D7BDF124056C.html" target="_blank">define ORM mappings, refer to this livedocs page to find out more.</a> Here are my three hibernate mapping cfcs.</p>
<p><strong>doctor.cfc</strong></p>
<pre class="brush: coldfusion; title: ; notranslate">
&lt;cfcomponent persistent=&quot;true&quot; entityname=&quot;Doctor&quot; table=&quot;providers&quot;&gt;
    &lt;cfproperty name=&quot;id&quot; column=&quot;provider_id&quot; generator=&quot;increment&quot;&gt;

    &lt;!--- one to many relationship Doctor.practice = Practice ---&gt;
    &lt;cfproperty name=&quot;practice&quot; fieldtype=&quot;one-to-one&quot; cfc=&quot;PRACTICE&quot; fkcolumn=&quot;practice_id&quot;&gt;

    &lt;cfproperty name=&quot;PracticeId&quot; column=&quot;practice_id&quot; insert=&quot;false&quot; update=&quot;false&quot;&gt;

    &lt;cfproperty name=&quot;FirstName&quot; column=&quot;first_name&quot;&gt;
    &lt;cfproperty name=&quot;LastName&quot; column=&quot;last_name&quot;&gt;
    &lt;cfproperty name=&quot;status&quot; column=&quot;status&quot;&gt;
    &lt;cfproperty name=&quot;is_midlevel&quot; column=&quot;is_midlevel&quot;&gt;
&lt;/cfcomponent&gt;
</pre>
<p><strong>practice.cfc</strong></p>
<pre class="brush: coldfusion; title: ; notranslate">
&lt;cfcomponent persistent=&quot;true&quot; entityname=&quot;Practice&quot; table=&quot;practices&quot;&gt;
	&lt;!--- tie this column back to Doctor.practice_id ---&gt;
	&lt;cfproperty name=&quot;id&quot; column=&quot;practice_id&quot; fieldtype=&quot;id&quot; generator=&quot;foreign&quot; params=&quot;{property='Doctor'}&quot;&gt;

	&lt;!--- Relate locations to this practice via Locations.practice_id and Locations.active = 1 ---&gt;
        &lt;cfproperty name=&quot;locations&quot; type=&quot;array&quot; fieldtype=&quot;one-to-many&quot; cfc=&quot;Location&quot; fkcolumn=&quot;practice_id&quot; params=&quot;{property='Location'}&quot; where=&quot;active = 1&quot;&gt;

    &lt;cfproperty name=&quot;name&quot; column=&quot;practice_name&quot;&gt;
    &lt;cfproperty name=&quot;active&quot; column=&quot;active&quot;&gt;
&lt;/cfcomponent&gt;
</pre>
<p><strong>location.cfc</strong></p>
<pre class="brush: coldfusion; title: ; notranslate">
&lt;cfcomponent persistent=&quot;true&quot; entityname=&quot;Location&quot; table=&quot;locations&quot;&gt;
	&lt;cfproperty name=&quot;id&quot; column=&quot;location_id&quot; fieldtype=&quot;id&quot;&gt;

	&lt;cfproperty name=&quot;practice_id&quot; column=&quot;practice_id&quot;&gt;

    &lt;cfproperty name=&quot;address1&quot; column=&quot;address1&quot;&gt;
    &lt;cfproperty name=&quot;address2&quot; column=&quot;address2&quot;&gt;
    &lt;cfproperty name=&quot;city&quot; column=&quot;city&quot;&gt;
    &lt;cfproperty name=&quot;state&quot; column=&quot;state&quot;&gt;
    &lt;cfproperty name=&quot;zipcode&quot; column=&quot;zipcode&quot;&gt;
    &lt;cfproperty name=&quot;phone&quot; column=&quot;phone&quot;&gt;
    &lt;cfproperty name=&quot;active&quot; column=&quot;active&quot;&gt;
&lt;/cfcomponent&gt;
</pre>
<p>At this point we have three ORM entities that are mapped to the three database tables.  If you look closely, you&#8217;ll notice that relationships have also been defined for doctors to practice, and practice to locations.  Setting up the relationships at the mapping level takes care of physically joining the three tables together via sql.  Also, while it&#8217;s pretty straight forward reading a blog with working code, I&#8217;m not going to pretend I got these relationships setup first try.  It&#8217;s simple relating two tables together, but finding the right combination for doctror &gt; practice &gt; locations was tricky.  I did a lot of this to figure this part out.</p>
<pre class="brush: coldfusion; title: ; notranslate">
&lt;cfscript&gt;
// load doctors
dr_list = ORMExecuteQuery( &quot;FROM Doctor WHERE status = 'Active' AND provider_id = 1&quot; );
// load a practice
// practice = ORMExecuteQuery( &quot;FROM Practice WHERE practice_id = 1&quot; );
// load a location
// location = ORMExecuteQuery( &quot;FROM Location&quot; );
&lt;/cfscript&gt;

&lt;cfdump var=&quot;#dr_list#&quot; /&gt;
&lt;cfabort /&gt;
</pre>
<p><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 19px; white-space: normal; font-size: 13px;">You can find out more about <a title="How to define relationships with Coldfusion9 ORM" href="http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WS5FFD2854-7F18-43ea-B383-161E007CE0D1.html" target="_blank">defining ORM relationships on this livedocs page</a>.</span></p>
<p>With the hard stuff out of the way, we&#8217;re down to two steps.  First it&#8217;s time to port my cfquery that grabs the data, and the cffunction that converts the query into our loopable doctor structure.  Are you ready for this?</p>
<pre class="brush: coldfusion; title: ; notranslate">
dr_list = ORMExecuteQuery( &quot;from Doctor WHERE status = 'Active' AND is_midlevel = 0 ORDER BY last_name, first_name&quot; );
</pre>
<p>To give you the full idea of how much code was shrunk down to a single line, here are the two cffunctions used to query and massage the data into a useable structure.</p>
<pre class="brush: coldfusion; title: ; notranslate">
	&lt;!--- Retrieve listing of all active providers in the app  ---&gt;
    &lt;cffunction name=&quot;getAllActiveProviders&quot; access=&quot;public&quot; returntype=&quot;struct&quot;&gt;

		&lt;cfquery name=&quot;providers_qry&quot; DATASOURCE=&quot;#request.dsn#&quot; USERNAME=&quot;#request.dbuser#&quot; PASSWORD=&quot;#request.dbpswd#&quot;&gt;
            SELECT	DISTINCT

					p.provider_id,
            		CONCAT( p.first_name, ' ', p.last_name ) AS 'full_name',
                    p.first_name,
                    p.last_name,

    	            p2.practice_name,

					l.address1,
                    l.address2,
                    l.city,
                    l.state,
                    l.zipcode,
                    l.phone

            FROM	providers p, practices p2

            LEFT OUTER JOIN locations l
            ON p2.practice_id = l.practice_id AND l.active = 1

            WHERE	p.status = 'Active'
            AND		p.practice_id = p2.practice_id
            AND		is_midlevel = 0

            ORDER BY	p.last_name, p.first_name
        &lt;/cfquery&gt;

		&lt;!--- return a translated structure ---&gt;
		&lt;cfreturn providersQryToStruct( providers_qry ) /&gt;

    &lt;/cffunction&gt;

	&lt;!--- Translates the providers query into a Struct that has a row per doctor, each containing an Array for location(s) ---&gt;
	&lt;cffunction name=&quot;providersQryToStruct&quot; access=&quot;public&quot; returntype=&quot;struct&quot;&gt;

    	&lt;cfargument name=&quot;providers_qry&quot; type=&quot;query&quot; required=&quot;yes&quot;&gt;

		&lt;cfscript&gt;
		this_dr = &quot;&quot;;
		last_dr = &quot;&quot;;
		// array of provider arrays
		providers_struct = StructNew();

		// loop through qry and flatten into single row with Location = Array
		// The key to this qry is provider_name+provider_id
		for( xx = 1; xx &lt;= providers_qry.RecordCount; xx++ )
		{
			// set key to this row [ LAST_NAME+FIRST_NAME+PROVIDER_ID ]
			this_dr = providers_qry.LAST_NAME[ xx ] &amp; providers_qry.FIRST_NAME[ xx ] &amp; providers_qry.PROVIDER_ID[ xx ];

			// clean up DR name
			this_dr = Replace( this_dr, &quot; &quot;, &quot;&quot; );
			this_dr = Replace( this_dr, &quot;,&quot;, &quot;&quot; );
			this_dr = Replace( this_dr, &quot;.&quot;, &quot;&quot; );

			// got same doctor?
			if( this_dr != last_dr )
			{
				// append to array
				provider = StructNew();
				// FILL UP PROVIDER
				provider['full_name'] = providers_qry[&quot;full_name&quot;][ xx ];
				provider['practice_name'] = providers_qry['practice_name'][ xx ];

				// location array
				provider['location'] = ArrayNew(1);

				// add first location
				loc = StructNew();
				loc['address1']	 = providers_qry['address1'][ xx ];
				loc['address2']	 = providers_qry['address2'][ xx ];
				loc['city']		 = providers_qry['city'][ xx ];
				loc['state']	 = providers_qry['state'][ xx ];
				loc['zipcode']	 = providers_qry['zipcode'][ xx ];
				loc['phone']	 = providers_qry['phone'][ xx ];

				// add location struct to array
				ArrayAppend( provider['location'], loc );

				// Add to master struct
				providers_struct[ this_dr ] = provider;
			}
			else
			{
				// add first location
				loc = StructNew();
				loc['address1']	 = providers_qry['address1'][ xx ];
				loc['address2']	 = providers_qry['address2'][ xx ];
				loc['city']		 = providers_qry['city'][ xx ];
				loc['state']	 = providers_qry['state'][ xx ];
				loc['zipcode']	 = providers_qry['zipcode'][ xx ];
				loc['phone']	 = providers_qry['phone'][ xx ];

				// Append to this DR's location array
				ArrayAppend( providers_struct[ this_dr ]['location'], loc );
			}

			// store this_dr in last_dr for next iteration
			last_dr = this_dr;
		}

		return providers_struct;
        &lt;/cfscript&gt;

    &lt;/cffunction&gt;
</pre>
<p>After going through the brain fry of figuring out ORM relationships, replacing over one hundred lines of code with only a single line really made my day.  Now it was time for the final step, porting the cfml that draws the html table into using the ORM collection instead.<br />
The porting of the cfml that draws the doctor table was a piece of cake.  The updates were so easy it was almost not worth showing, but I&#8217;m including just to complete the picture.</p>
<p><strong>The original sql loop code</strong></p>
<pre class="brush: coldfusion; title: ; notranslate">
    &lt;!--- use dr_list as sorted list. use each DR key to pick out data from providers_struct ---&gt;
    &lt;cfloop list=&quot;#dr_list#&quot; index=&quot;xx&quot;&gt;
    &lt;tr&gt;

        &lt;td&gt;#providers_struct[ xx ]['full_name']#&lt;/td&gt;

        &lt;td&gt;#providers_struct[ xx ]['practice_name']#&lt;/td&gt;

        &lt;td&gt;
        &lt;!--- loop through array of location structures ---&gt;
        &lt;cfloop from=&quot;1&quot; to=&quot;#ArrayLen( providers_struct[ xx ]['location'] )#&quot; index=&quot;yy&quot;&gt;
            &lt;address&gt;
            &lt;cfset loc = #providers_struct[ xx ]['location'][ yy ]#&gt;
            &lt;li&gt;#loc.address1#, #loc.address2#
            #loc.city#, #loc.state# #loc.zipcode#
            &lt;br /&gt;
            &lt;b&gt;#loc.phone#&lt;/b&gt;
            &lt;/li&gt;
            &lt;/address&gt;
        &lt;/cfloop&gt;
        &lt;/td&gt;

    &lt;/tr&gt;
    &lt;/cfloop&gt;
</pre>
<p><strong>The new ORM loop code</strong></p>
<pre class="brush: coldfusion; title: ; notranslate">
	&lt;!--- loop through parent query ---&gt;
    &lt;cfloop array=&quot;#dr_list#&quot; index=&quot;xx&quot;&gt;
    &lt;tr&gt;

    	&lt;!--- retrieve properties using ORM's getProperty() syntax ---&gt;
        &lt;td&gt;#xx.getFirstName()# #xx.getLastName()#&lt;/td&gt;

        &lt;td&gt;#xx.getPractice().getName()#&lt;/td&gt;

        &lt;td&gt;
		&lt;!--- loop through locations collection Doctor &gt; Practice &gt; Location(s)  ---&gt;
        &lt;cfloop array=&quot;#xx.getPractice().getLocations()#&quot; index=&quot;loc&quot;&gt;

            &lt;address&gt;
                &lt;li&gt;#loc.getAddress1()#, #loc.getAddress2()#
                #loc.getCity()#, #loc.getState()# #loc.getZipcode()#
                &lt;br /&gt;
                &lt;b&gt;#loc.getPhone()#&lt;/b&gt;
                &lt;/li&gt;
            &lt;/address&gt;

        &lt;/cfloop&gt;
        &lt;/td&gt;

    &lt;/tr&gt;
    &lt;/cfloop&gt;
</pre>
<p>A few things I&#8217;d like to point out in the new ORM loop code</p>
<ol>
<li>ORMExecuteQuery returned a data collection that I can loop through without post-processing</li>
<li>When retrieving object properties, use the get<strong>PropertyName</strong>() syntax.  EX : doctor.getFirstName() instead of doctor.FirstName</li>
<li>Practice.locations was declared as an Array collection, but you could use Structure as well.</li>
<li>To get the ORMExecuteQuery record count, use ArrayLen.</li>
</ol>
<h2>Did ORM make this easier?</h2>
<p>I&#8217;d say yes it did.  Mapping my tables via code, including the relationships, really saved time writing SQL.  Funny thing, while I was porting this over, I actually found a few data and code bugs in the home grown solution that I didn&#8217;t catch before.  Once the dust had settled I still had one difference in the home grown versus ORM code, and that turned out to be duplicated location rows.</p>
<p>The other thing that I noticed thanks to our good friend cfdump, is all the extra functionality that comes along with the objects returned from ORM.  On top of having a populated data object, you also have magical getters, setters, and other useful methods to work with your data objects.  To see what I mean, fire an ORMExecuteQuery and run your variable through CFDUMP.</p>
<p>To sum up, I&#8217;m really starting to buy into using ORMs.  Since I know and love SQL, I&#8217;ve been anti ORM for too long.  Having said that, I&#8217;m not fully advocating going ORM for everything.  Pretty much every project I work on these days is powered by some datasource, but I don&#8217;t really need all the ORM baggage for simple sites.  Now for large applications, or any site large enough to need at least two people, I&#8217;d give ORM a chance.  I still have lots of ins and outs to learn about using Hibernate, but it is definitely simple enough to get jamming right away.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2009/12/i-wonder-if-using-coldfusion9s-orm-would-make-this-easier/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

