Can someone help me understand why automatic identification (int) is bad when using NHibernate?

I saw a lot of comments (from NHibernate's point of view) about using Guid as opposed to int (and presumably auto-id in the database), with the conclusion that using auto-identity violates the UoW pattern.

There is a brief description of the problem in this post , but it doesn’t really tell me why, it breaks the pattern (unless I misunderstand what is likely to occur.

Can someone enlighten me?

+4
source share
3 answers

There are several main reasons.

  • Using Guid gives you the opportunity to identify a single object in many databases, including six relational databases with the same schema, but different data, a document database, etc. This becomes important at any time when you have more than one place where the data goes - and that also means your business: you have a dev database and a prod database, right?

  • Using Guid gives NHibernate the ability to simultaneously execute several commands, do a lot of work with databases at the very end of a unit of work / transaction, and reduce the total number of database calls, increasing productivity and other benefits.

Comment:

Random Guid do not create bad indexes - initially they create bad clustered indexes. There are two solutions.

  • Use a partially sequential Guid . With NHibernate, this means using the id generator guid.comb rather than the id Guid generator. guid.comb is partially consistent for good performance, but retains a very high degree of randomness.

  • The primary key of Guid should be the nonclustered index, and the clustered index should be in another auto-increment column. You can select this column, in which case you will lose the advantage of a better dosage and less rounding, but you will get all the advantages of short numbers that fit easily into the URL. Or you may decide not to display this column and leave it completely in the database, in which case you will get better performance for Guid as primary keys, as well as better performance for NHibernate, which performs fewer hits.

+4
source

My assumption would be that the key factor of the gap is that in order to get an automatically incremented value, an actual write to the database is required, which nHibernate would defer or possibly never execute.

+3
source

Using the identifier and in the parent-child scenario, the database has feedback from the database in order to obtain the identifier of the parent so that it can correctly associate the child. This means that the parent must be perfect at this time. If there is a problem with the child, you will need to remove the parent in order to correctly exit UoW.

+1
source

All Articles