views:

642

answers:

2

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?

A: 

Don't you need this?

<query-param name='UserId' type='Integer'/>
Ehrann Mehdan
My code works without it using Darin's answer. However will also try your answer with <query ...> and get back to later.
Rippo
+2  A: 

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>
Darin Dimitrov
aha, just saw your edit. I see now that there is a difference between <query> and <sql-query> Many thanks.
Rippo