Get a memento of a Entity's data
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.
- Posted in:
- ColdFusion
- Hibernate


Comment by Sam Farmer – March 16, 2010
Does this return inherit properties?
ListLast(GetMetaData(this).fullname, ".") might not work if the entity has entityName="XYZ"
Comment by Henry – March 16, 2010
Comment by Ben Nadel – March 17, 2010
@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
the getMemento() ive written sees if its not simple.
if not, create a key in the memento of entityname & entity pri key name, using getIdentifierPropertyName(), then grab the value of it.
Comment by aaron – December 10, 2010
Comment by John Whish – December 11, 2010