【问题标题】:NHibernate use Stored Procedure OR mappingNHibernate 使用存储过程 OR 映射
【发布时间】:2011-06-16 13:58:28
【问题描述】:

我在 NHibernate 中有一个像这样工作的映射:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="BizEntities"
    namespace="BizEntities"
    default-lazy="false">
  <class name="SubscriberQueueItem" table="SubscriberQueueItem">
    <id name="SubscriberQueueItemId" column="Id" type="int" unsaved-value="0">
      <generator class="identity" />
    </id>
    <property name="DateCreated" column="DateCreated"  type="DateTime" />
    <property name="CMIId" column="CMIId" type="int" />
    <property name="DateProcessed" column="DateProcessed"  type="DateTime" />
    <property name="EventStatus" column="EventStatusId" type="QueueStatusTypeValues, BizEntities" />
    <many-to-one  name="Subscription"  class="Subscription" column="SubscriptionId" />
    <property name="ErrorDescription" column="ErrorDescription" type="string" />

  </class>
</hibernate-mapping>

它是通过对表的简单查询来检索的。

是否也可以将此类映射到存储过程?我编写了一个过程,它返回一个特定的数据子部分,这些数据很难写入 NHibernate 查询,但作为存储过程很容易编写。

我是否可以简单地添加一个存储过程映射作为回答 here,并根据我的 NHibernate 查询类型使用直接映射或存储过程检索对象,或者向我的 hbm 添加一个存储过程映射意味着我只能检索基于在那个存储过程上?

【问题讨论】:

  • 我不确定你想要实现什么,但我认为这两件事是相互排斥的。你可以看看ayende 的帖子:ayende.com/blog/1728/…

标签: c# nhibernate


【解决方案1】:

存储过程在 NHibernate 中工作得很好,我使用它们没问题 :)

您需要将“命名查询”添加到您的休眠映射中,如下所示:

<sql-query name="spMyProcedure">
    <!-- return type must be an NHibernate mapped entity -->
    <return alias="SubscriberQueueItem" type="BizEntities.SubscriberQueueItem, BizEntities" />

    exec spMyProcedure @Param1=:Param1, @Param2=:Param2
</sql-query>

如果存储过程的返回类型与已映射的实体不匹配,则需要创建一个新的。

要调用 sp,您需要添加以下代码:

var query = session.GetNamedQuery("spMyProcedure");

query.SetParameter("Param1", "hello");
query.SetParameter("Param2", "byebye");

SubscriberQueueItem result = query.UniqueResult<SubscriberQueueItem>();

【讨论】:

  • 所以为这样的选择添加命名查询不会阻止您执行正常的 NHibernate 映射(不使用存储过程)?太棒了!
  • 不,你仍然可以在适当的地方直接访问表:)
  • NHibernate-mapping XSD 没有为 元素定义“类型”属性。 hibernatingrhinos.googlecode.com/svn/trunk/Caching/SharedLibs/…
  • @AdolfoPerez 自从我回答这个问题以来,这似乎在 3 年多的时间里发生了变化。如果您有更多最新信息,请告诉我们:)
猜你喜欢
  • 2010-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-19
相关资源
最近更新 更多