Today I ran into a situation in a nHibernate based project where I needed to execute a very specialized query. Using HQL was rather not practical since I had to query tables which were not "directly" mapped to entities.
So, if you need execute queries behind nHibernate's back and map the results to a Bean / Object not specified in the mappings, You might come up with a solution like this:
string someComplexQuery = @"select ... from ..."; IQuery sqlQuery = sessionFactory.GetCurrentSession().CreateSQLQuery(someComplexQuery). AddScalar("Id", NHibernateUtil.Int32). AddScalar("Firstname", NHibernateUtil.String). AddScalar("Lastname", NHibernateUtil.String).SetResultTransformer( IList<Person> people = sqlQuery.List<Person>(); foreach (Person person in people) { // ... }
class Person { private long id; private string firstname; private string lastname; public long Id { get { return id; } set { id = value; } } public string Firstname { get { return firstname; } set { firstname = value; } } public string Lastname { get { return lastname; } set { lastname = value; } } }
Comments
java variant
here goes an example for the java variant of hibernate:
P.S.
I ran into an issue with the column name aliasing and hibernate 3.1 - got me a unknown column name afterwards. perhaps a bug, not sure. bottom line is: you might need to name you bean properties after the column names and not use "AS" in the sql query.