Get a memento of a Entity's data

March 16, 2010

I can't take the credit for this - it was Sam Farmer's suggestion, but I thought it was so damn cool that I'm going to blog it anyway :)

A question was asked on the cf-orm mailing list about getting the data from a persisted Entity (CFC) as JSON. 

This was my suggestion:


<cffunction name="getMemento" output="false" returntype="struct">
<cfset var properties = ORMGetSessionFactory().getAllClassMetadata()[ ListLast( GetMetaData( this ).fullname, "." ) ].getPropertyNames()>
<cfset var memento = {}>
<cfset var result = "">
<cfloop array="#properties#" index="item">
<cfinvoke component="#this#" method="get#item#" returnvariable="result">
<cfif IsNull(result)>
<cfset memento[item] = "">
<cfelse>
<cfset memento[item] = result>
</cfif>
</cfloop>
<cfreturn memento>
</cffunction>

Then Sam posted this:


<cffunction name="getMemento" output="false" returntype="any">
<cfreturn SerializeJSON( this )>
</cffunction>

I really like this - very clean. This lead me to think that if I wanted the data as a structure instead of JSON I can simply do:


<cffunction name="getMemento" output="false" returntype="struct">
<cfreturn DeserializeJSON( SerializeJSON( this ) )>
</cffunction>

It is worth noting that when you use Entities in ColdFusion, under the hood it's powered by Hibernate and has the concept of null values. So if a property hasn't had a value assigned to it then it is null and will not appear in your struct. If you do need to see all the properties, then my original suggestion may be the solution for you.


4 comments

  1. @John -- glad you liked it and found it cool! :)

    Comment by Sam Farmer – March 16, 2010
  2. var properties = ORMGetSessionFactory().getAllClassMetadata()[ ListLast( GetMetaData( this ).fullname, "." ) ].getPropertyNames()

    Does this return inherit properties?

    ListLast(GetMetaData(this).fullname, ".") might not work if the entity has entityName="XYZ"

    Comment by Henry – March 16, 2010
  3. Funky - I had no idea you could actually do that.

    Comment by Ben Nadel – March 17, 2010
  4. @Sam, yeah I would never have thought of using SerializeJSON :)

    @Henry, ListLast will return the only element in a list if the delimiter is not found, so ListLast( "myentity", "." ) will return "myentity". As for inherited properties, short answer is I haven't tried it. Long answer is I don't see why it shouldn't :)

    @Ben, you and me both dude :)

    Comment by John Whish – March 18, 2010

Leave a comment

If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Please note: If you haven't commented before, then your comments will be moderated before they are displayed.