开发者

NHibernate: Using a custom type as a primary key

开发者 https://www.devze.com 2023-01-26 08:19 出处:网络
I have a legacy schema that contains tables with primary keys of type binary(16) -- its a MD5 hash of the other columns. NHibernate does not work with byte[] as a key since it does not implement Equal

I have a legacy schema that contains tables with primary keys of type binary(16) -- its a MD5 hash of the other columns. NHibernate does not work with byte[] as a key since it does not implement Equals so I wrapped this in a custom type and provided NHibernate wit开发者_如何学Ch an implementation of IUserType. Notice that MD5Hash is a struct and not a class.

public struct MD5Hash : IComparable, IComparable<MD5Hash>, IEquatable<MD5Hash> {
    private readonly byte[] contents;
    ...
}

Everything worked fine until I created a many-to-one mapping to a type that uses MD5Hash as its key.

public class Referenced : IEquatable<Referenced> {
    ...
    public virtual MD5Hash Id { get; set; }
    public virtual string Name { get; set; } // must NOT be null
    ...
}

public class Referencer : IEquatable<Referencer> {
    ...
    public virtual MD5Hash Id { get; set; }
    public virtual Referenced Other { get; set } // may be null
    ...
}

When I attempt to load objects of type Referencer, NHibernate does not see a null value for the key when the row contains a NULL value so it attempts to instantiate an object of type Referenced, assign it to Referencer, and update Referencer in the database. Since Referenced has a property, Name, which maps to a non-nullable column, NHibernate raises an exception. What I want is for NHibernate to set the Other property to null.

I could change the definition of MD5Hash to be a class instead of a struct but I have an unknown number of places in the code that probably assumes MD5Hash can never be null so I am looking for another solution.

The code for the custom type...

internal class MD5HashType : IUserType {
    public SqlType[] SqlTypes {
        get { return new[] { new SqlType(DbType.Binary, 16) }; }
    }

    public Type ReturnedType {
        get { return typeof(MD5Hash); }
    }

    public new bool Equals(object x, object y) {
        return Object.Equals(x, y);
    }

    public int GetHashCode(object x) {
        return (null == x) ? 0 : x.GetHashCode();
    }

    public object NullSafeGet(IDataReader rs, string[] names, object owner) {
        var val = NHibernateUtil.Binary.NullSafeGet(rs, names[0]);
        return (null == val || DBNull.Value == val) ? MD5Hash.Empty : new MD5Hash((byte[])val);
    }

    public void NullSafeSet(IDbCommand cmd, object value, int index) {
        var val = (MD5Hash.Empty == ((MD5Hash)value)) ? null : ((MD5Hash)value).ToByteArray();
        NHibernateUtil.Binary.NullSafeSet(cmd, val, index);
    }

    public object DeepCopy(object value) {
        return value;
    }

    public bool IsMutable {
        get { return false; }
    }

    public object Replace(object original, object target, object owner) {
        return original;
    }

    public object Assemble(object cached, object owner) {
        return cached;
    }

    public object Disassemble(object value) {
        return value;
    }
}


The problem appears to be that NHibernate can't tell that MD5Hash.Empty means no value. Have you tried creating custom event listeners such as the following to handle this? Something like:

public class CustomLoadListener : DefaultLoadEventListener {
    public override void OnLoad(LoadEvent @event, LoadType loadType) {
        if(@event.EntityId is MD5Hash) {
            var id = (MD5Hash) @event.EntityId;
            if(id == MD5Hash.Empty) {
                @event.Result = new Referenced { Id = MD5Hash.Empty };
                return;
            }
        }
        base.OnLoad(@event, loadType);
    }
}

public class CustomSaveOrUpdateListener : DefaultSaveOrUpdateEventListener {
    public override void OnSaveOrUpdate(SaveOrUpdateEvent @event) {
        var entity = @event.Entity as Referenced;
        if(entity != null && entity.Id == MD5Hash.Empty) {
            return;
        }
        base.OnSaveOrUpdate(@event);
    }
}

You would then have to configure these listeners in your session factory via hibernate.cfg.xml:

<session-factory>
    <!-- various properties -->
    <listener type="load" class="NhHacking.CustomLoadListener, NhHacking"/>
    <listener type="save-update" class="NhHacking.CustomSaveOrUpdateListener, NhHacking"/>
</session-factory>

If someone has a better idea of how to accomplish this, I would love to hear it.

0

精彩评论

暂无评论...
验证码 换一张
取 消