Woah, Nellie.NET!

From my simple mind to… mine…

Simple NHibernate Example, Part 3: Initial Repository Implementation

leave a comment »

Repositories are our central access point to pre-existing domain objects. Repositories simplify the management of the object’s life cycle and decouple the domain from data access technologies and strategies. Finally, repositories are domain level, communicating to other domain objects how certain objects can be accessed.

I will begin my initial repository implementation by exploring how to save (register) a NEW domain object with our repository, thus giving that object Identity within the context of our domain.

Let’s say that we have a new auto Dealer object. The auto dealer’s information has been entered into the domain object and we are not ready to persist that information into the domain.

Our initial specifications for the repository are the following. For this initial implementation, I am going to use a mocked interface representing the repository. This will allow us to explore the interactions between the domain object and the Repository interface. Eventually, we will replace this mocked interface code with the real NHibernate implementation.

    1 using Foo.Domain;
    2 using Foo.Domain.Repositories;
    3 using NUnit.Framework;
    4 using Rhino.Mocks;
    6 namespace Specifications.Foo.Domain
    7 {
    8     [TestFixture]
    9     public class WhenSavingANewDealerToTheDealerRepository
   10     {
   11         private const int MOCK_DB_ID = 1;
   12         private Dealer dealer;
   13         private MockRepository mocks;
   14         private DealerRepository dealerRepository;
   16         [SetUp]
   17         public void SetUpContext()
   18         {
   19             dealer = new Dealer();
   20             mocks = new MockRepository();
   21             dealerRepository = mocks.CreateMock<DealerRepository>();
   22         }
   24         [Test]
   25         public void ShouldPopulateAnIdForTheDealerAfterSaving()
   26         {
   27             SetupMockExpectations();
   29             Assert.AreEqual(0, dealer.Id, "The dealer's ID should not be set before the save.");
   30             Dealer savedDealer = dealerRepository.Save(dealer);
   32             Assert.IsNotNull(savedDealer, "A saved dealer reference should be returned from the Repository.");
   33             Assert.AreNotEqual(dealer, savedDealer, "The saved dealer reference should be different from the one passed into the Save.");
   34             Assert.AreEqual(MOCK_DB_ID, savedDealer.Id, "A system ID should be generated for the newly saved dealer.");
   35             mocks.VerifyAll();
   36         }
   38         private void SetupMockExpectations()
   39         {
   40             Dealer dealerToReturnInExpectedCall = SetupExpectationThatACallToSaveWillReturnANewDealerReference();
   41             SetupExpectationThatTheIdOnTheNewDealerReferenceWillBeSet(dealerToReturnInExpectedCall);
   42             mocks.ReplayAll();
   43         }
   45         private static void SetupExpectationThatTheIdOnTheNewDealerReferenceWillBeSet(Dealer dealerToReturnInExpectedCall)
   46         {
   47             Expect.Call(dealerToReturnInExpectedCall.Id).Return(MOCK_DB_ID);
   48         }
   50         private Dealer SetupExpectationThatACallToSaveWillReturnANewDealerReference()
   51         {
   52             Dealer dealerToReturnInExpectedCall = mocks.PartialMock<Dealer>();
   53             Expect.Call(dealerRepository.Save(dealer)).Return(dealerToReturnInExpectedCall);
   54             return dealerToReturnInExpectedCall;
   55         }
   56     }
   57 }

As an explanation:

  • I am going to make a technical implementation decision (let me know if this is wrong) and return a new Dealer object reference from the save call (line 30). Simliar to NHibernate, I believe, this will allow for the return of the proxied reference, which is managed by NHibernate (mocked on lines 52 and 53). This is a significant point and I hope to have some time to verify this in another post.

  • The Dealer.Id property cannot be set externally (please review my previous post on Identity), so on line 47, I used Rhino mocks to partially mock the interface and return a value for that property.
  • On line 33, the expectation is meant to show that the original reference to the Dealer domain object is not the same as the new “proxied” version.

This defines the basic specification for the interface:

namespace Foo.Domain.Repositories
    public interface DealerRepository
        Dealer Save(Dealer dealer);

Time to begin implementation of the repository interface with NHibernate. I’ll create an NHibernate mapping file to begin with.

Assume that our database (in Sql Server 2005) and Dealer table with a DealerId column are in place. Also, this example uses NHibernate 1.2.0CR1 released on 2/22/07. I downloaded the latest version for some of the newest functionality, including generics and null types.

The table definition:

The simplest NHibernate mapping file to match our specifications will look like this:

<?xml version=1.0 encoding=utf-8 ?>
hibernate-mapping xmlns=urn:nhibernate-mapping-2.0>
class name=Foo.Domain.Dealer, Foo.Domain table=Dealer>
id name=Id column=DealerId>
generator class=assigned />

Basically, all this says is to map the Dealer domain property, Id, to the column DealerId in the database table Dealer. It also says to utilize the database table’s identity capabilities to generate the unique ID for the domain object.

Here is how I’ve structured the project. The Dealer mapping file is called Dealer.hbm.xml. There are references to the project containing the domain and the repository interface. There is also a reference to the NHibernate.dll file. The DealerRepository listed below is implementing the DealerRepository interface from the domain (code coming up shortly):

And be sure to include the Dealer.hbm.xml as an embedded resource:

I’ve jumped the gun a bit, so in the next posting, I’ll begin with writing NHibernate unit tests that interface with the database. The process is somewhat involved for the initial implementation, but once setup, it should be reusable for all database unit tests going forward.


Written by Nelson

April 2, 2007 at 3:35 am

Posted in NHibernate

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: