문제

In my MSSQL server I have a SQL view called AllFavourite. In order to load the data into my DTO class I have the following in my hbm.xml file...

<?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>

In my code I have the following.

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>();
}

This works great and produces the results that I am after, however I would like to move the SQL from code into a named query into the hbm.xml file. So my hbm.xml file now looks like this

<?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>

and my code now looks like this

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

However when I run this I get an error:-

Parameter UserId does not exist as a named parameter in [SELECT * FROM AllFavourite WHERE UserId=:UserId]

So my question is it possible to use a named query in this manner?

도움이 되었습니까?

해결책

The query tag expects a HQL query:

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

If you want to write a native sql query you should use the sql-query tag:

<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>

다른 팁

Don't you need this?

<query-param name='UserId' type='Integer'/>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top