Samuel Adam
Samuel Adam

Reputation: 1337

NHibernate save non-persisted entity while maintaining the existing ID

It's not a really common case, but in this particular one the task is to accomplished this :

  1. Serialize a list of existing entities loaded with NHibernate in database A
  2. Export the serialized entities to a file
  3. Import the serialized entities file to database B, using NHibernate as the persisting agent

The problem is the entities maps is marked with Id generator :

public class EntityMap
{
    public EntityMap()
    {
        Id(x => x.Id)
            .GeneratedBy.Guid();
        // Other properties
    }
}

With that mapping, everytime I called :

ISession session = NHibernateSession.GetSession();
IList<Entity> entities = // Load entity from serialized object in a file

foreach(entity in entities)
{
    session.Save(entity);
}

NHibernate keeps generating a new Id for those entities.

Is there a way to keep the mapping having Id generation strategy, but somehow able to persist an existing entity with it's Id predefined?

Upvotes: 0

Views: 407

Answers (1)

Oskar Berggren
Oskar Berggren

Reputation: 5629

The logic here is simple:

You want to have application-assigned identifiers. Therefore, you should configure NHibernate for application-assigned identifiers.

What you're asking is basically to tell NHibernate to generate the identifiers for you, but then insisting to do it yourself anyway.

One can also note that NHibernate isn't really intended as a replication tool. Have you considered serializing the entities to an SQL script instead, that you can simple execute on the target database? That would circumvent NHibernate's id assignment.

For doing distributed database, my suggestions are: To begin with, I would look to see if the database system itself have any sort of replication/data stream/data mirror that could be used for this. If that didn't work, I would probably try to write something similar - that is, bypass NH on the read side as well, just do simple table reads and write out INSERT statements to a file, that the recipient can apply. This works as long as there are no or few data transformations required. If the data needs complex transformations (which couldn't be avoided)... well if the logic gets complex enough we get back to doing it through NH.

Another way is to try to capture the input that modifies the original database (e.g. command pattern), and pass that same input to all the other databases also. Essentially letting each system react to the input - with a deterministic system and the same input, all databases will end up in the same state.

Upvotes: 1

Related Questions