2011-06-16 87 views
3

我有NHibernate的映射工作方式类似于这样: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意味着我只能检索基于该存储过程?

回答

6

存储过程中NHibernate的工作只是罚款,我使用的是他们没有问题:)

你需要添加一个“命名查询”到你的Hibernate映射,像这样:

<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>(); 
+0

因此,为这样的选择添加一个命名查询并不妨碍你做正常的NHibernate映射(不使用存储过程)?优秀! – Jeff 2011-06-16 15:21:29

+0

不,你仍然可以在适当的地方直接访问表格:) – MattDavey 2011-06-16 15:49:03

+0

NHibernate映射XSD没有为元素定义'type'属性。 http://hibernatingrhinos.googlecode.com/svn/trunk/Caching/SharedLibs/nhibernate-mapping.xsd – 2014-12-02 18:50:14

0

我不确定你想达到什么,但我认为这两件事是相互排斥的。

你可能会对ayende帖子一看:http://ayende.com/blog/1728/should-you-use-nhibernate-with-stored-procedure

+0

我认为这是说什么,我想达到的目的:我希望能够进行正常的查询对“SubscriberQueueItem”表,我也希望能够通过存储过程检索SubscriberQueueItem对象。 – Jeff 2011-06-16 15:18:12