Using a named query in a hbm with import class

Rippo picture Rippo · Dec 31, 2009 · Viewed 8.7k times · Source

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?

Answer

Darin Dimitrov picture Darin Dimitrov · Dec 31, 2009

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>