Spring4D ORM Change Tracking

Spring4D’s ORM uses an instance of an IEntityMap to perform change tracking. The default implementation is essentially a threadsafe wrapper around a Dictionary that uses an entitykey of the classname + ‘$’ + the object Id and the Value portion is an array of member values. If an object instance is present in the EntityMap, IsMapped() returns True.

As objects are mapped from ResultSets, they are added to the the EntityMap capturing their values as read from the database. If you want to see what changes were made to the objects you must call GetChangedMembers() which returns a list of attributes for columns that have changed. In effect Spring4D keeps two copies of the data for a given object: the data in the object instance itself and the EntityMap, which is a reasonably compact version of the data as it was originally read from the database result set.

hcOPF takes a different approach, in that each object instance essentially has 2 identical field variables for each attribute and a boolean field to track Nulls. The advantage of this approach is that you can easily test each attribute to see if it’s NULL or has been changed, in user code without testing all of them. Since the implementation does not use RTTI it is likely faster, and hcOPF Attributes surface change notifications. Of course the trade off is larger object instances.

Change Notifications are a very powerful mechanism for both the framework and developer code. They can be used to trigger attribute level validations, provide GUI feedback of modification status and provide for very granular efficient calculations on attributes. In fact these change notifications are the basis for hcOPF’s ability to save an object graph to the database by simply calling object.Save on the root object.  Some frameworks like mORMot have even implemented database auditing tracking.

Sadly, Change Notifications are something missing from the Spring4D ORM. If you want to know if a an object has been Modified you can of course add a FModified boolean field and set it in each property setter after checking if the value being set differs from the current value. It’s a roll your own state tracking that you would expect the ORM to do for you, and it doesn’t take into account situations where the user modifies an object property and then changes it back either by Undoing the change, or changing it back to the original value.

In developer code, change notifications can dramatically simplify logic to save data when the application allows users to modify numerous root objects with the ability to undo changes. It can become quite difficult to determine what method calls are required to save all changes with Spring4D when you don’t know what has been changed in the first place.

Leave a Reply