Over a million developers have joined DZone.

Using structures/maps instead of arrays in ORM

· Java Zone

Learn more about the advantages of moving from a monolithic to microservices architecture.  Brought to you in partnership with IBM.

By default an ORM relationship is an array. Using a structure (map for non-ColdFusion programmers) is very easy and provides nice options. Lets start with a simple relationship between of users and addresses.
component persistent="true" {
property name="userId" fieldtype="id" generated="always" generator="native";
property name="name" ormtype="string";

property name="address" fieldtype="one-to-many" cfc="address" fkcolumn="userId" inverse="true";
component persistent="true" {
property name="addressId" fieldtype="id" generated="always" generator="native";
property name="type" ormtype="string";
property name="street" ormtype="string";
property name="city" ormtype="string";
property name="state" ormtype="string";

property name="user" fieldtype="many-to-one" cfc="user";

A single user object with two addresses would look like this:

Now, if we want to find out if the user has a work address we need to loop through getAddress(). Thats ok but by converting the relationship to a struct its possible to then use structure functions. Here is the relationship in User.cfc defined to return a structure:

property name="address" fieldtype="one-to-many" cfc="address" fkcolumn="userId" inverse="true"
    type="struct" structkeycolumn="type";

A dump of the user object now looks like:

Which means we can use code like this, in particular line 3:

<cfset u = entityLoad("user")>
<cfloop array="#u#" index="user">
    <cfif structKeyExists( user.getAddress(), "work" )>
        <cfdump var="#user.getAddress()["work"]#">

For reference here is the Application.cfc to set up Hibernate/ORM:

this.ormsettings = { dbcreate="update" };


From Idea to Application gives you the architecture to quickly build, manage and run a range of applications (web, mobile, big data, new smart devices, etc.) on an open-standard, cloud-based platform. See why developers are using IBM Bluemix. Brought to you in partnership with IBM.


Published at DZone with permission of Sam Farmer, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}