A good deed
4 comments Published Oct 20, 2008 by Miroslav Popovic in agile, NHibernateLooks like I did a good deed today :)
And despite Stephen's words, I did it out of gratitude, not out of pity :)
Repository implementation
0 comments Published Oct 16, 2008 by Miroslav Popovic in DDD, NHibernateAlong with NHibernate mappings, Peniko.DataLayer project contains Repository implementations. Repository interfaces are in Peniko.Domain project, as mentioned before.
All communication with NHibernate is done through ISession instance. Session is basically a Unit of Work for NHibernate. We have a standard NHibernateHelper static class for encapsulating ISessionFactory and for creating / opening the session:
public static class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
var configuration = new Configuration();
configuration.Configure();
configuration.AddAssembly(typeof(Product).Assembly);
_sessionFactory = configuration.BuildSessionFactory();
}
return _sessionFactory;
}
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
SessionFactory is created from the NHibernate configuration the first time its accessed. Configuration comes from hibernate.cfg.xml file defined in UI and test projects:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">...</property>
<property name="show_sql">true</property>
<mapping assembly="Peniko.DataLayer" />
</session-factory>
</hibernate-configuration>
In Peniko.DataLayer, every Repository method uses its own session, so we can't use NHibernate's lazy loading feature. Better option would be session-per-conversation pattern mentioned here, but we'll leave it as is for now.
The most important class in Repository implementation is Repository<T> implementing our IRepository<T> interface:
public interface IRepository<T> where T : Entity<T>
{
void Save(T entity);
void Delete(T entity);
T GetById(Guid id);
IList<T> GetAll();
}
public abstract class Repository<T> : IRepository<T> where T : Entity<T>
{
private static readonly ILog _log = LogManager.GetLogger(typeof (Repository<T>));
protected static ILog Log { get { return _log; } }
public void Save(T entity) { ... }
public void Delete(T entity) { ... }
public T GetById(Guid id) { ... }
public IList<T> GetAll() { ... }
}
It's defined as abstract class and provides inherited classes with basic strongly typed methods for saving, deleting and retrieving all entities or a single entity by id and also an log4net's ILog instance . Inherited class is defined like this:
public class ProductRepository : Repository<Product>, IProductRepository { ... }
This is a Save method from Repository<T>:
public void Save(T entity)
{
if (!entity.IsValid) throw new ValidationException("Entity is invalid");
using (var session = NHibernateHelper.OpenSession())
using (var transaction = session.BeginTransaction())
{
Log.DebugFormat("Saving entity Id: {0}", entity.Id);
try
{
session.SaveOrUpdate(entity);
AfterSaveEntity(session, entity);
transaction.Commit();
}
catch (StaleObjectStateException ex)
{
transaction.Rollback();
Log.Error("Error saving entity", ex);
throw new ConcurrencyException("The data has been modified by another user", ex);
}
catch (HibernateException ex)
{
transaction.Rollback();
Log.Error("Error saving entity", ex);
throw;
}
}
}
First thing it does is to check if entity is valid. Then it opens a session and begins a new transaction on it. As of NHibernate 2.0, all Saves, Updates and Deletes must be encapsulated in transaction. Save method calls session.SaveOrUpdate() which does both insert and update operations based on the value of entity.Id. In our case, if Id is Guid.Empty, it will do Insert, otherwise Update.
AfterSaveEntity call allows inherited class to do some action after the entity is saved successfully. I.e. to save some other, unrelated entity.
Note that we catch StaleObjectStateException. That exception is thrown when there is a concurrency problem. We encapsulate it in our ConcurrencyException and throw that instead. That way it's easy to catch it in UI code without dependency on NHibernate.
Delete method is more or less the same. The only difference is that it calls session.Delete() instead of session.SaveOrUpdate().
GetById looks like this:
public T GetById(Guid id)
{
using (var session = NHibernateHelper.OpenSession())
{
Log.DebugFormat("Getting entities with Id: {0}", id);
try
{
var entity = session.Get<T>(id);
AfterGetEntity(session, entity);
return entity;
}
catch (HibernateException ex)
{
Log.Error("Error getting entities by id", ex);
throw;
}
}
}
This method is very simple. session.Get<T>(id) returns a single entity with the given id. GetAll method is similar, but it uses NHibernate Criteria API and returns session.CreateCriteria(typeof (T)).List<T>() as a result.
In another project I'm currently involved, Repository also has FindAll and FindOne methods that accept DetachedCriteria as a parameter. The idea came from 12. episode of Summer of NHibernate.
Other Repository classes inherited from Repository<T> have its own methods for retrieving entities. These methods are mostly using Criteria API. More on Criteria API and HQL in NHibernate learning material.
Mapping entities with NHibernate
6 comments Published by Miroslav Popovic in NHibernate
The next thing to be done was NHibernate mapping. Mappings are defined in Peniko.DataLayer project.
Every entity class has its own mapping file. Mapping file is named after a class, so if class name is Category, the mapping file is Category.hbm.xml. hbm stands for Hibernate mapping. Having this naming scheme is not required, but NHibernate will try to look for these names automatically when mapping. If you want to name your mappings differently, then you'll need to tell that to NHibernate.
Mapping file must have Embedded Resource build action. That's the thing that gets easily forgotten, so double check all your mapping files.
Writing a mapping file can be tedious and error-prone, but there is a cure for that. NHibernate comes with two XML schema files (nhibernate-configuration.xsd and nhibernate-mapping.xsd) that you can copy to Program Files\Microsoft Visual Studio 9.0\Xml\Schemas. Once there, they'll provide you with Intelli-sense when writing NHibernate mappings and configuration in Visual Studio.
If you are ReSharper user, there is also a nice ReSharper NHibernate plugin. It checks type, assembly and property names and allows navigation to mapped classes with Ctrl+Click on class or property name. Also, any renames are reflected in mapping file.
Below is an example of a very simple mapping:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Peniko.Domain"
namespace="BLDotNet.Peniko.Domain">
<class name="Category" table="Categories">
<id name="Id" column="CategoryId">
<generator class="guid" />
</id>
<property name="Name" column="Name" length="50" not-null="true" unique="true" />
</class>
</hibernate-mapping>
You must fully qualify type names in mapping files ("Namespace.Class, Assembly"), or you can define assembly and namespace attributes on root tag.
If the table name differs from the class name, there has to be a table attribute on <class> tag. In our case, all table names are plural.
id must be defined for all mapped classes. There are different id generators in NHibernate, but you'll most likely choose between "guid" and "native". When "native" generator is selected, NHibernate will use database generated value - this is an identity field in SQL Server. NHibernate maintains ids itself, so you don't have to ever assign values to them (unless you are using "assigned" generator).
All simple properties are mapped with <property> tag. There are also <many-to-one>, <one-to-one> and <one-to-many> tags for relations with other mapped classes; <subclass> and <joined-subclass> for inheritance mapping; <map>, <set>, <list> and <bag> for collection mapping and even more tags.
This should be enough to get you started with NHibernate mapping. For more details see NHibernate learning material.
NHibernate learning material
1 comments Published Aug 1, 2008 by Miroslav Popovic in DDD, NHibernateWe started off by learning NHibernate. Up until then I didn't use any OR/M (I don't consider LINQ 2 SQL to be a full OR/M). Most of the time, the code I wrote used ADO.NET DataReaders, alone or inside CSLA.NET DataPortal_xxx methods.
Since there is a lot of buzz lately about OR/Ms, Entity Framework is about to be released, it already got a vote of no confidence from ALT.NET group, etc, the good learning material isn't so hard to find. When I'm learning something new, I'm trying to find and use best good practices, established by the people who have been used that technology for a longer time. The following posts/articles/screencasts really helped me and my team to get on the right track.
The NHibernate FAQ by Gabriel Schenker is a great starting point:
- Prepare your system for NHibernate
- Your first NHibernate based application
- Lazy Loading - Eager Loading
- Identity Field, Equality and Hash Code
- How to setup a new solution
- Eager loading aggregate with many child collections
- Soft Deletes
- NHibernate and the Unit of Work Pattern
- NHibernate and the Unit of Work Pattern (Part 2)
- NHibernate and the Unit of Work pattern (Part 3)
- NHibernate and Castle Active Record (Part 1)
- Create and Update Database Schema
- Loading a complex object graph
- How to map a tree in NHibernate
- Mapping Collections in NHibernate (Part 1)
- How to configure Log4Net for use with NHibernate
Steve Bohlen's excellent screencast series Summer of NHibernate.
Ben Scheirman's series of articles about NHibernate and Domain Driven Design:
- A Journey with NHibernate - Part 1
- A Journey With NHibernate - Part 2
- A Journey With NHibernate (and DDD) - Part 3
- A Journey with Domain Driven Design (and NHibernate) - Part 4
- A Journey with Domain Driven Design (and NHibernate) - Part 5
- A Journey with Domain Driven Design (and NHibernate) - Part 6
- A Journey with Domain Driven Design (and NHibernate) - Part 7
- A Journey with Domain Driven Design (and NHibernate) - Part 8
- A Journey with Domain Driven Design (and NHibernate) - Part 9
Davy Brion's NHibernate posts.
THE article NHibernate Best Practices with ASP.NET by Billy McCafferty. I'm looking forward for a chance to try his S#arp Architecture on a real project.
David Veeneman's NHibernate Made Simple article.
All of the above links will not only teach you how to use NHibernate, but also give you a start with Domain Driven Design, Unit Testing, Integration Testing, logging etc. Enjoy!
Blog Archive
My Blog List
-
Scratch a simple data model, find a complex one3 months ago
-
-
Native AOT libraries with TypeScript3 years ago
-
-
-
-
-
Cake Build Tool8 years ago
-
ASP.NET hosting with lifetime 50% off13 years ago
-
-
-
-
-
