Persistence Ignorant Objects with ActiveRecord

Posted by Jack Altiere on July 8th, 2008

In my last article, I wrote about how to get ActiveRecord to handle reading and writing data to the database.  Now that we know how to handle that, it’s time to clean up the example.  One problem with my business entity classes is that they had specific knowledge about how they were loaded and saved.  For example, I had methods like this one in my Contact class:

   1:  public static Contact LoadContactById(int contactID)
   2:  {
   3:      return FindOne(Expression.Eq(“ContactID”, contactID));
   4:  }

The problem with this is that this couples our business objects with our persistence strategy, namely ActiveRecord.  This makes it really difficult to get rid of this down the road if we choose to, violating a design goal of making our software loosely coupled.  If you’ve written software for any period of time, the one thing you can count on is that requirements change.   What seems locked in stone today might need to be completely replaced tomorrow, which is why we need to make design decisions that make changes like this easier.

Another reason to separate our persistence strategy from our business objects is that it just looks cleaner.  You have less code in your objects dealing with how they are loaded and stored, and the code that is left deals with the actual business rules.  How can we accomplish this goal?

The first thing I think of is some sort of repository to do the job.  I’ll make this an interface, that way our options for a persistence strategy are left open.  We’ll start out small, and just give the interface one method to load the business object from it’s primary key.  At this point we have a choice.  We could make a repository for each business object to specialize them, or we could make a generic repository to try and handle all cases.   I’ll go with the latter method and just create a single repository.

   1:  namespace ActiveRecordSample
   2:  {
   3:     public interface IRepository
   4:     {
   5:        T LoadById<T>(int key) where T : class;
   6:     }
   7:  }

For my repository definition, I will create an ActiveRecord repository:

   1:  namespace ActiveRecordSample
   2:  {
   3:     public class ActiveRecordRepository : IRepository 
   4:     {
   5:        #region IRepository Members
   6:        public T LoadById<T>(int key) where T : class
   7:        {
   8:           return ActiveRecordMediator<T>.FindByPrimaryKey(key, true);
   9:        }
  10:        #endregion
  11:     }
  12:  }

I had to add the type constraint to my method in the interface because ActiveRecordMediator<T> requires T to be a reference type.   This methodology allows me to pull out all of the persistence methods from my business objects, and I will be able to load any of my business objects by their ID without any additional code. 

   1:  // Instantiate the repository.
   2:  ActiveRecordRepository repository = new ActiveRecordRepository();
   3:   
   4:  Order ord = repository.LoadById<Order>(43659);
   5:  Product prod = repository.LoadById<Product>(1);
   6:  Employee emp = repository.LoadById<Employee>(1001);

 

In the above example, I’m loading Orders, Products and Employees using the same repository method.  (for a refresher on the definitions of my business objects, see my previous article)   OK, that’s great…but you might be saying to yourself that we don’t really have much of a repository here.  What if we want to find any order in July of 2001?  Or any user with a last name that starts with A?  How can the repository possibly handle these situations?

Well, this is sort of a trick question.  This can be done fairly easily by adding a method to our interface, making our interface and implementation look like this:

   1:  public interface IRepository
   2:  {
   3:     T LoadById<T>(int key) where T : class;
   4:     IList<T> FindResults<T>(ICriterion[] criteria) where T : class;
   5:  }
   6:   
   7:  public class ActiveRecordRepository : IRepository 
   8:  {
   9:     #region IRepository Members
  10:     public T LoadById<T>(int key) 
  11:              where T : class
  12:     {
  13:        return 
  14:           ActiveRecordMediator<T>.FindByPrimaryKey(key, true);
  15:     }
  16:   
  17:     public IList<T> FindResults<T>(ICriterion[] criteria) 
  18:              where T : class
  19:     {
  20:        return ActiveRecordMediator<T>.FindAll(criteria);
  21:     }
  22:     #endregion
  23:  }

We could then answer the questions I posed above fairly easily like this:

   1:  // Find all employees whose last name starts with ‘A’
   2:  expr.ICriterion[] criteria = new expr.ICriterion[]
   3:  {
   4:     expr.Expression.Like(“LastName”, “A%”)
   5:  };
   6:   
   7:  IList<Employee> emps = 
   8:       repository.FindResults<Employee>(criteria);
   9:   
  10:  // Find all the orders in July 2001
  11:  DateTime start = new DateTime(2001, 7, 1);
  12:  DateTime end = new DateTime(2001, 7, 31);
  13:   
  14:  criteria = new expr.ICriterion[]
  15:  {
  16:     expr.Expression.Between(“OrderDate”, start, end)
  17:  };
  18:   
  19:  IList<Order> ords = 
  20:       repository.FindResults<Order>(criteria);

 

A little note about the above code…..I created an alias to the NHibernate.Expression namespace called expr to avoid namespace naming conflicts.  The problem with this solution is that we’ve just created a leaky abstraction.  We now made our repository depend on the NHibernate .dll because we used the interface NHibernate.Expression.ICriterion as a parameter to our method.  This makes it hard to ever replace NHibernate if the need arises.

There are a few ways we can fix the leaky abstraction.  We could either create a repository for each business object, or we could write a wrapper for the ICriterion parameter that would allow us to abstract the dependency on NHibernate away.  If we choose to create a repository for each business object, the example above would look something like this:

 

   1:  public interface IEmployeeRepository
   2:  {
   3:     Employee LoadById(int id);
   4:     IList<Employee> LoadByLastName(char letter);
   5:  }
   6:   
   7:  public interface IOrderRepository
   8:  {
   9:     Order LoadById(int id);
  10:     IList<Order> LoadByDateRange(DateTime start, DateTime end);
  11:  }
  12:   
  13:  public class AREmployeeRepository : IEmployeeRepository
  14:  {
  15:     #region IEmployeeRepository Members
  16:     public Employee LoadById(int id)
  17:     {
  18:        return 
  19:           ActiveRecordMediator<Employee>.FindByPrimaryKey(id, true);
  20:     }
  21:   
  22:     public IList<Employee> LoadByLastName(char letter)
  23:     {
  24:        ICriterion[] criteria = new ICriterion[]
  25:        {
  26:           Expression.Like(“LastName”, letter + “%”)
  27:        };
  28:   
  29:        return ActiveRecordMediator<Employee>.FindAll(criteria);
  30:     }
  31:     #endregion
  32:  }
  33:   
  34:  public class AROrderRepository : IOrderRepository
  35:  {
  36:     #region IOrderRepository Members
  37:     public Order LoadById(int id)
  38:     {
  39:        return 
  40:           ActiveRecordMediator<Order>.FindByPrimaryKey(id, true);
  41:     }
  42:   
  43:     public IList<Order> LoadByDateRange(DateTime s, DateTime e)
  44:     {
  45:        ICriterion[] criteria = new ICriterion[]
  46:        {
  47:           Expression.Between(“OrderDate”, s, e)
  48:        };
  49:   
  50:        return ActiveRecordMediator<Order>.FindAll(criteria);
  51:     }
  52:     #endregion
  53:  }

Notice how our interfaces no longer depend on NHibernate, so loose coupling is achieved.  The downside to this approach is that there are more interfaces to maintain, and you need to create a method for every operation that you want to support.  This is an example of how these repositories could be used:

   1:  AREmployeeRepository employeeRepository =
   2:      new AREmployeeRepository();
   3:   
   4:  Employee emp = 
   5:     employeeRepository.LoadById(1001);
   6:   
   7:  IList<Employee> emps = 
   8:     employeeRepository.LoadByLastName(‘A’);
   9:   
  10:  AROrderRepository orderRepository = 
  11:     new AROrderRepository();
  12:   
  13:  Order ord = orderRepository.LoadById(43659);
  14:   
  15:  DateTime start = new DateTime(2001, 7, 1);
  16:  DateTime end = new DateTime(2001, 7, 31);
  17:  IList<Order> orders = 
  18:     orderRepository.LoadByDateRange(start, end);

The benefit to this that we achieve loose coupling, which allows me to completely replace NHibernate and / or ActiveRecord if I ever want a different persistence solution.  I should point out, we would still need to modify our business entities we wanted to completely replace our persistence solution, since all of our classes are using ActiveRecord attribute decoration….but this would hopefully be a relatively painless task.  We could also introduce a dependency injection framework to further promote loose coupling. (Ninject comes immediately to mind as a great choice here)  This would allow us to bind our repository at run time and not have to instantiate a specific implementation of our repositories every time we want to use them.  

kick it on DotNetKicks.com

ActiveRecord and NHibernate

Posted by Jack Altiere on July 1st, 2008

In my first article in this series, I touched on using NHibernate and performed a few simple examples.  In the second, I added some complexity and introduced relationships, inheritance, etc.  In this article I want to see how we can use Castle’s ActiveRecord to potentially simplify things.

After downloading the Castle installation .msi from the website, I decided to just jump right in to the Quickstart guide to get things going.  Once again, I’ll be working with the AdventureWorks database if you want to follow along.  After creating a class library, I added a reference to these .dll’s to get things started:

  • Castle.ActiveRecord.dll
  • Castle.Core.dll
  • Castle.Components.Validator.dll
  • Castle.DynamicProxy.dll
  • NHibernate.dll
  • Iesi.Collections.dll
  • log4net.dll

    Next, I want to create a sample class.  It looks like using ActiveRecord is going to eliminate the need for me to hand write the .xml mapping files that I had to create when I used NHibernate by itself, which is a plus.  I decided to stick with the same example I used in my first NHibernate article and I created a Contact class.

     

       1:  [ActiveRecord("Person.Contact")]
       2:  public class Contact : ActiveRecordBase<Contact>
       3:  {
       4:     private int _contactID;
       5:     private string _firstName;
       6:     private string _middleName;
       7:     private string _lastName;
       8:     private string _email;
       9:     private DateTime _lastModified;
      10:   
      11:     [PrimaryKey]
      12:     public int ContactID
      13:     {
      14:        get { return _contactID; }
      15:        set { _contactID = value; }
      16:     }
      17:   
      18:     [Property]
      19:     public string FirstName
      20:     {
      21:        get { return _firstName; }
      22:        set { _firstName = value; }
      23:     }
      24:   
      25:     [Property]
      26:     public string MiddleName
      27:     {
      28:        get { return _middleName; }
      29:        set { _middleName = value; }
      30:     }
      31:   
      32:     [Property]
      33:     public string LastName
      34:     {
      35:        get { return _lastName; }
      36:        set { _lastName = value; }
      37:     }
      38:   
      39:     [Property("EmailAddress")]
      40:     public string Email
      41:     {
      42:        get { return _email; }
      43:        set { _email = value; }
      44:     }
      45:   
      46:     [Property("ModifiedDate")]
      47:     public DateTime LastModified
      48:     {
      49:        get { return _lastModified; }
      50:        set { _lastModified = value; }
      51:     }
      52:   
      53:     public Contact()
      54:     {
      55:   
      56:     }
      57:  }

    I’m liking this a whole lot better than just using NHibernate by itself.  I’m not a fan of writing .xml files for each class to map it to a table, and the use of attributes feels a lot cleaner to me.   Notice on line 1 where  decorate my class with the ActiveRecord attribute, and I pass in the table name.  My class must also inherit from ActiveRecordBase.  In the class itself, I am able to specify my primary key with the [PrimaryKey] attribute, and I can specify all of the properties that map to database columns with the [Property] attribute.  On a few of my properties the table name does not match the database column name, so in these cases I just pass in the correct column name via the attribute.

    I couldn’t escape XML configuration completely however, I need to tell ActiveRecord how to connect to my database, and specify configuration options to pass through to NHibernate.  There are a few ways to do this, I chose to add it into my app.config file, making it look like this:

       1:  <?xml version=”1.0″ encoding=”utf-8″ ?>
       2:  <configuration>
       3:    
       4:    <configSections>
       5:      <section name=”activerecord”
       6:        type=”Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, 
       7:                         Castle.ActiveRecord” />
       8:    </configSections>
       9:   
      10:    <activerecord
      11:          isWeb=”false”
      12:          isDebug=”true”>
      13:      <config>
      14:        <add key=”hibernate.connection.driver_class” 
      15:          value=”NHibernate.Driver.SqlClientDriver” />
      16:        <add key=”hibernate.dialect”                 
      17:          value=”NHibernate.Dialect.MsSql2005Dialect” />
      18:        <add key=”hibernate.connection.provider”     
      19:          value=”NHibernate.Connection.DriverConnectionProvider” />
      20:        <add key=”hibernate.connection.connection_string” 
      21:          value=”Server=localhost;initial catalog=AdventureWorks;Integrated Security=SSPI” />
      22:      </config>
      23:    </activerecord>
      24:      
      25:  </configuration>

    There are a lot of options available when setting up your configuration.  If you want to dig into all of the different configuration options, this is a great place to start.  There is one more step necessary before you can start using ActiveRecord.  We have already set up our class, and we also have set up the necessary configuration….the only thing that remains is to initialize ActiveRecord.  This is only done one time, and my code to handle initialization looks like this:

       1:  IConfigurationSource config = 
       2:            ActiveRecordSectionHandler.Instance;
       3:  ActiveRecordStarter.Initialize(config, typeof(Contact));

    That wasn’t so bad, was it?  You do need to tell ActiveRecord which types it needs to initialize.   The reason for this is because ActiveRecord handles all of the mapping between the database and NHibernate, so it needs to know which types need set up.  I passed in the one type I had set up, but there are several ways to handle this.  You can pass in a list of types, an assembly, or a list of assemblies.  In fact, since I don’t want to have to remember to come back to add in any new types I set up, I’ll change this to load my assembly instead….making it look like this:

       1:  IConfigurationSource config = 
       2:          ActiveRecordSectionHandler.Instance;
       3:  Assembly asm = Assembly.Load(“ActiveRecordSample”);
       4:  ActiveRecordStarter.Initialize(asm, config);

    Now that everything is configured and initialized, it’s time to try and use it.  The first thing I want to be able to do is load a contact based on their ContactID.   This turns out to be really simple.  Using NHibernate expressions, I can query the database however I want to.  Recall that my Contact class inherits from ActiveRecordBase, which gives me access to several static methods for the loading and saving of data.

    I could put the query directly in my console application, like this:

       1:  Contact ct = 
       2:        Contact.FindOne(Expression.Eq(“ContactID”, 24));
       3:  StringBuilder sb = new StringBuilder();
       4:  sb.AppendLine(“First Name: “ + ct.FirstName);
       5:  sb.AppendLine(“Middle Name: “ + ct.MiddleName);
       6:  sb.AppendLine(“Last Name: “ + ct.LastName);
       7:  sb.AppendLine(“Email: “ + ct.Email);
       8:  Console.WriteLine(sb.ToString());

    There are a few reasons I don’t like this.  First, I have to add a reference to the NHibernate.dll in my console application, which couples my UI and data layer together.  Second, I would have to rely on anyone using this class to know how to write HQL (Hibernate Query Language) expressions to load this data.  I don’t think that’s necessarily a fair assumption to make, so the better solution in my mind is to abstract this out.  If you were paying attention to the class diagram above, you’ll notice that I already created a method in my Contact class called LoadContactById which looks like this:

       1:  public static Contact LoadContactById(int contactID)
       2:  {
       3:     return FindOne(Expression.Eq(“ContactID”, contactID));
       4:  }

    I could then modify my console application to load the Contact like this:

       1:  Contact ct = Contact.LoadContactById(24);
       2:  StringBuilder sb = new StringBuilder();
       3:  sb.AppendLine(“First Name: “ + ct.FirstName);
       4:  sb.AppendLine(“Middle Name: “ + ct.MiddleName);
       5:  sb.AppendLine(“Last Name: “ + ct.LastName);
       6:  sb.AppendLine(“Email: “ + ct.Email);
       7:  Console.WriteLine(sb.ToString());

    This also allows me to remove the reference to the NHibernate .dll from my console application, which is better design to me anyway.  This gives us the expected result, and the data is loaded correctly:

    If you remember my last article, one thing we tried was to set up an inheritance structure and have NHibernate successfully load the data from multiple tables. ActiveRecord can also handle this scenario by using the JoinedBase attribute.  After I set up the Contact class to use the JoinedBase attribute, I just need to create my Employee class.  When I set this up, I have to set up a JoinedKey, which is the column that joins the two tables together. 

       1:  // This is the only change I made to the contact class.
       2:  [ActiveRecord("Person.Contact"), JoinedBase]
       3:   
       4:  [ActiveRecord("HumanResources.Employee")]
       5:  public class Employee : Contact
       6:  {
       7:     private int _contactID;
       8:     private int _employeeID;
       9:     private string _title;
      10:     private DateTime _hireDate;
      11:     private bool _salaryFlag;
      12:   
      13:     [JoinedKey("ContactID")]
      14:     public int CID
      15:     {
      16:        get { return _contactID; }
      17:        set { _contactID = value; }
      18:     }
      19:   
      20:     [Property]
      21:     public int EmployeeID
      22:     {
      23:        get { return _employeeID; }
      24:        set { _employeeID = value; }
      25:     }
      26:   
      27:     [Property]
      28:     public string Title
      29:     {
      30:        get { return _title; }
      31:        set { _title = value; }
      32:     }
      33:   
      34:     [Property]
      35:     public DateTime HireDate
      36:     {
      37:        get { return _hireDate; }
      38:        set { _hireDate = value; }
      39:     }
      40:   
      41:     [Property("SalariedFlag")]
      42:     public bool SalaryFlag
      43:     {
      44:        get { return _salaryFlag; }
      45:        set { _salaryFlag = value; }
      46:     }
      47:   
      48:     public Employee()
      49:        : base()
      50:     {
      51:   
      52:     }
      53:   
      54:     public static Employee LoadEmployeeByContactId(int contactID)
      55:     {
      56:        return (Employee)FindOne(Expression.Eq(“ContactID”, contactID));
      57:     }
      58:   
      59:     public static Employee LoadEmployeeByEmployeeId(int employeeID)
      60:     {
      61:        return (Employee)FindOne(Expression.Eq(“EmployeeID”, employeeID));
      62:     }
      63:  }

    Loading an employee works as expected, and I put together wrapper methods to load an employee by either the ContactID or the EmployeeID.  (since they are different in the AdventureWorks schema)

    Now it’s time for the fun part……relationships.  In my previous article I set up an object graph where I had an Order object, which contained a collection of OrderDetail objects, each of which encapsulated a Product object.  I want to duplicate that same idea using ActiveRecord.  This turns out to be incredibly intuitive, and the classes end up looking like this:

       1:  [ActiveRecord("Sales.SalesOrderHeader")]
       2:  public class Order : ActiveRecordBase<Order>
       3:  {
       4:     private int _orderID;
       5:     private DateTime _orderDate;
       6:     private decimal _orderTotal;
       7:     private IList _lineItems;
       8:   
       9:     [PrimaryKey("SalesOrderID")]
      10:     public int OrderID
      11:     {
      12:        get { return _orderID; }
      13:        set { _orderID = value; }
      14:     }
      15:   
      16:     [Property]
      17:     public DateTime OrderDate
      18:     {
      19:        get { return _orderDate; }
      20:        set { _orderDate = value; }
      21:     }
      22:   
      23:     [Property("TotalDue")]
      24:     public decimal OrderTotal
      25:     {
      26:        get { return _orderTotal; }
      27:        set { _orderTotal = value; }
      28:     }
      29:   
      30:     [HasMany(typeof(OrderDetail), Table="Sales.SalesOrderDetail", 
      31:            ColumnKey="SalesOrderID")]
      32:     public IList LineItems
      33:     {
      34:        get { return _lineItems; }
      35:        set { _lineItems = value; }
      36:     }
      37:   
      38:     public Order()
      39:     {
      40:   
      41:     }
      42:   
      43:     public static Order LoadOrderById(int orderID)
      44:     {
      45:        return FindOne(Expression.Eq(“OrderID”, orderID));
      46:     }
      47:  }
      48:   
      49:  [ActiveRecord("Sales.SalesOrderDetail")]
      50:  public class OrderDetail
      51:  {
      52:   
      53:     private int _orderDetailID;
      54:     private int _quantity;
      55:     private string _trackingNumber;
      56:     private decimal _price;
      57:     private Product _item;
      58:   
      59:     [PrimaryKey("SalesOrderDetailID")]
      60:     public int OrderDetailID
      61:     {
      62:        get { return _orderDetailID; }
      63:        set { _orderDetailID = value; }
      64:     }
      65:   
      66:     [Property("OrderQty")]
      67:     public int Quantity
      68:     {
      69:        get { return _quantity; }
      70:        set { _quantity = value; }
      71:     }
      72:   
      73:     [Property("CarrierTrackingNumber")]
      74:     public string TrackingNumber
      75:     {
      76:        get { return _trackingNumber; }
      77:        set { _trackingNumber = value; }
      78:     }
      79:   
      80:     [Property("UnitPrice")]
      81:     public decimal Price
      82:     {
      83:        get { return _price; }
      84:        set { _price = value; }
      85:     }
      86:   
      87:     [BelongsTo("ProductID")]
      88:     public Product Item
      89:     {
      90:        get { return _item; }
      91:        set { _item = value; }
      92:     }
      93:   
      94:     public OrderDetail()
      95:     {
      96:   
      97:     }
      98:  }
      99:   
     100:  [ActiveRecord("Production.Product")]
     101:  public class Product
     102:  {
     103:     private int _productID;
     104:     private string _name;
     105:     private string _productNumber;
     106:   
     107:     [PrimaryKey]
     108:     public int ProductID
     109:     {
     110:        get { return _productID; }
     111:        set { _productID = value; }
     112:     }
     113:   
     114:     [Property]
     115:     public string Name
     116:     {
     117:        get { return _name; }
     118:        set { _name = value; }
     119:     }
     120:   
     121:     [Property]
     122:     public string ProductNumber
     123:     {
     124:        get { return _productNumber; }
     125:        set { _productNumber = value; }
     126:     }
     127:   
     128:     public Product()
     129:     {
     130:   
     131:     }
     132:  }

    To encapsulate the Product inside the OrderDetail, I need to use the BelongsTo attribute.  To make the association, all I need to pass into this attribute is the name of the database column that ties the tables together.  In my case, the Sales.SalesOrderDetail table contains a clear foreign key to the Production.Product table, so I pass in “ProductID”.  The relationship mapped out in the Order class is even more intuitive.  I use the HasMany relationship to indicate that one order has many line items.  To complete this association, I pass in the table name of the order detail table and the column name of the field that serves as the foreign key, and ActiveRecord does the rest.  A complete list of ActiveRecord relationships and how they work can be found here.

    To load an order, I wrote a wrapper method in my Order class called LoadOrderById that takes care of it.  Calling this function will load the entire object graph.  This might not be the intended behavior, especially if you have a large and / or complex object graph.  For cases like this, lazy loading is possible with ActiveRecord.  I’m not going to get into the details here, but you can enable lazy loading on an ActiveRecord type or on a relation.  More details on how to do this can be found here.

    I can say that I’m very impressed with the implementation of ActiveRecord.  After giving it a try, I can say I’d never personally just use NHibernate again without it.  I love the fact that all of my mappings are taken care of with attributes rather than XML files, and relationships are very intuitive.  I’ve definitely only scratched the surface, but I think it’s safe to say that this product is definitely in my toolbox for good!

    kick it on DotNetKicks.com


  • Copyright © 2007 Jack Altiere. All rights reserved.