Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate Composite Key vs Composite Unique Constraint

When using NHibernate, if I have an entity that has a unique constraint and that can be identified uniquely by that constraint, is it better to represent the constraint as a composite key or have a seperate Id field and have a composite unique constraint? I have been reading that it is considered "bad" to use composite keys with NHibernate if it can helped and should only be used when working with legacy databases.

Image the setup as follows:

class Book
{
   public virtual int Id { get; protected set; }
   public virtual string Author { get; set; }
   public virtual IList<BookEdition> Editions { get; set; } //HasMany (one to many)
}

class BookEdition
{
   public virtual string Title { get; set; }
   public virtual string Language { get; set; }
   public virtual int Edition { get; set; }
}

Here we have a constraint for the BookEdition where it has a constraint on the Language and Edition, i.e. there can't be two editions of the book in the same language. Any edition can also be uniquely identified by an edition number and a language.

Which approach is considered better in NHibernate? Use the Language/Edition as a composite Id or introduce an Id variable for the BookEdition and have a composite unique constraint instead?

like image 337
Can Gencer Avatar asked Apr 18 '11 16:04

Can Gencer


1 Answers

Surrorgate key (additional Id variable) is better in general not only in NHibernate. The problem with natural keys (here: Language and Edition) is that they have a "business" meaning. Business needs evolve in time and you will certainly have to change your natural keys in the future, which could be very painful. Additionally your SQL joins and where conditions will be more complicated.

This could be FNH mapping of BookEdition with composite unique constraint:

    Id(x => x.Id);
    Map(x => x.Title);
    Map(x => x.Language).UniqueKey("MyCompositeUniqueConstraint");
    Map(x => x.Edition).UniqueKey("MyCompositeUniqueConstraint");

Btw. it is good practice to not show surrorgate key values to customers. They tend to assign some business meaning to them and then they want to change them as well:).

like image 79
Jakub Linhart Avatar answered Nov 10 '22 18:11

Jakub Linhart