在具有导入类的hbm中使用命名查询

时间:2009-12-31 08:41:03

标签: nhibernate class import named-query hbmxml

在我的MSSQL服务器中,我有一个名为AllFavourite的SQL视图。为了将数据加载到我的DTO类中,我在hbm.xml文件中有以下内容......

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
       namespace="Domain.Model.Entities" assembly="Domain.Model">
  <import class="AllFavourite"/>
</hibernate-mapping>

在我的代码中,我有以下内容。

public IList<AllFavourite> GetFavourites(int userId)
{
    var query = Session
        .CreateSQLQuery("SELECT * FROM AllFavourite where UserId=:UserId")
        .SetInt32("UserId", userId)
        .SetResultTransformer(new AliasToBeanResultTransformer(typeof(AllFavourite)));
    return query.List<AllFavourite>();
}

这很好用并产生我所追求的结果,但是我想将SQL从代码移动到命令查询到hbm.xml文件中。所以我的hbm.xml文件现在看起来像这个

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
namespace="Domain.Model.Entities" assembly="Domain.Model">
  <import class="AllFavourite"/>
  <query name="GetAllFavouriteByUserId">
    <![CDATA[
    SELECT * FROM AllFavourite WHERE UserId=:UserId
    ]]>
  </query>
</hibernate-mapping>

我的代码现在看起来像这样

public IList<AllFavourite> GetFavourites(int userId)
{
    var query = Session
        .GetNamedQuery("GetAllFavouriteByUserId")
        .SetInt32("UserId", userId)
        .SetResultTransformer(new AliasToBeanResultTransformer(typeof(AllFavourite)));
    return query.List<AllFavourite>();
}

然而,当我运行这个时,我收到一个错误: -

  

参数UserId不存在   [SELECT * FROM中的命名参数   AllFavourite WHERE UserId =:UserId]

所以我的问题是可以以这种方式使用命名查询吗?

2 个答案:

答案 0 :(得分:3)

query标记需要HQL查询:

<query name="GetAllFavouriteByUserId">
    <![CDATA[
    from AllFavourite where UserId = :UserId
    ]]>
</query>

如果要编写本机SQL查询,则应使用sql-query标记:

<sql-query name="GetAllFavouriteByUserId">
    <return alias="foo" class="Foo"/>
    <![CDATA[
    SELECT {foo.ID} as {foo.ID}, 
           {foo}.NAME AS {foo.Name} 
    FROM sometable 
    WHERE {foo}.ID = :UserId
    ]]>
</sql-query>

答案 1 :(得分:0)

你不需要这个吗?

<query-param name='UserId' type='Integer'/>