基于父类ID的NHibernate缓存对象 [英] NHibernate Caching Objects Based on Parent Class's ID

查看:91
本文介绍了基于父类ID的NHibernate缓存对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于动物和狗类型,我有以下定义.请注意,该对象的ID是AnimalID:

I have the following definitions for the Animal and Dog types. Note that the ID for the object is the AnimalID:

<class name="Animal" table="Animals">
    <id name="Id" type="System.Int32" column="AnimalID">
        <generator class="identity" />
    </id>
    <property name="IsBig" column="IsBig" type="System.Bool" not-null="true" />  
</class>

<joined-subclass name="Dog" table="Dogs" extends="Animal">
    <key column="AnimalID" />
    <property name="OwnerID" column="OwnerID" type="System.Int32" non-null="true" />
    <property name="IsStrong" column="IsStrong" type="System.Bool" non-null="true" />
</joined-subclass>

假设我的数据库中包含以下信息:

Let's say I have the following information in my database:

in table Animals:

AnimalID    IsBig
--------    -----
10          True

in table Dogs:

AnimalID    OwnerID    IsStrong
--------    -------    --------
10          1          True
10          2          False

首先,我查询OwnerID = 1的Dog.在同一会话中,我查询OwnerID = 2的Dog.由于NHibernate的会话缓存,第二个查询返回了一个Dog对象,其中OwnerID = 1和IsStrong =是的,它应该返回一个OwnerID = 2且IsStrong = False的Dog对象.

First, I query for the Dog where OwnerID = 1. In the same session, I query for the Dog where OwnerID = 2. Because of NHibernate's Session cache, the second query returns a Dog object where OwnerID = 1 and IsStrong = True, where it should return a Dog object where OwnerID = 2 and IsStrong = False.

NHibernate通过ID(主键)列自动缓存对象,因此第二次请求Dog最终以相同的键检索对象.我可以通过在对象上调用ISession.Evict()来解决此问题,但这似乎是一种hack.

NHibernate automatically caches objects by their ID (primary key) column, so requesting the Dog the second time ends up retrieving an object with the same key. I can solve this problem by calling ISession.Evict() on the object, but that seems like a hack.

还有更好的建议吗?

推荐答案

您必须确保对不同的实例使用不同的密钥.在您的情况下,您实际上违反了此规则:Dogs表公开了两个实例的一部分共享同一密钥.

You must ensure you're using different keys for different instances. In your case you're actually violating this rule: Dogs table exposes parts of two instances sharing the same key.

因此,必须将Dogs.AnimalID 标记为主键,但在您的情况下则不是.如果将其标记为PK,则根本无法获得此类内容.

So Dogs.AnimalID must be marked as primary key, but in your case it isn't. If it would be marked as PK, you couldn't get such content at all.

这篇关于基于父类ID的NHibernate缓存对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆