I’ve always had a soft spot for ORMs (Object Relational Mappers). Whilst opinion is divided on their use, I just love them. I’ve actually written a few, because I’ve never found exactly the right one for me. Currently in the Delphi world, there are a few open source ones, and some commercial ones, but all seem to have been started pre Delphi 2010. Which means they don’t support Attributes and the new RTTI. When I first saw Attributes in Delphi 2010, I thought ORM immediately. All the ORMs I’ve used or written (in Delphi at least) store their mapping information separate to the actual class that needs to be stored. One I used, stored the information in an XML file, which was read, and parsed on start up to produce a class map. So I thought, how would I do it with Attributes.
TTestObject = class(TPersistable)
fName : string;
function GetName: string;
procedure SetName(const Value: string);
property Name : string read GetName write SetName;
At it’s simplest, I have one attribute for the class, and another for each property I wish to persist. The PersistentClassAttribute, takes the table name, whilst the PersistentPropertyAttribute takes the column name and whether the column is a primary key. What I’m hoping for is if I try and save an object of type TTestObject I get the following SQL for my relational database.
INSERT INTO TestObject(IdCol, NameColumn) VALUES(2, 'Steve')
And if I try and load and object, by writing MyObject.Load(2), I’ll get SQL similar to the following.
SELECT IdCol, NameColumn FROM TestObject WHERE Id=2
Next time I’ll demonstrate how I use those attributes to create a class map