Blog Stats
  • Posts - 62
  • Articles - 1
  • Comments - 35
  • Trackbacks - 76

 

NHibernate Parameters and Escaping Special Characters in HQL

I am sure I everyone else knows this by now, but I wanted to jot a note. When you are passing strings to an HQL query, it's best practice to assign those strings to a parameter (named or positional) and let HQL escape the special characters for you. So it would look like this when searching by a Name and Distinction tag on an Entity:

            StringBuilder queryString = new StringBuilder();

 

            queryString.Append("from Entity e where e.Name= :name AND ");

            queryString.Append("e.DistinctionTag = :distinctionTag ");

 

            try

            {

                query.Match = Session.CreateQuery(queryString.ToString()).SetString("name",query.Name)

                                  .SetString("distinctionTag",query.DistinctionTag).UniqueResult() as IEntity;

            }

            catch (NonUniqueResultException)

            {

                query.Match = new NullEntity();

            }

            return query.Match;

The call to .SetString() is where we assign our parameters to our string values. This works for matching Custom Classes and even Custom Type Properties as well. Sweet.

Further Info
  • Hibernate in Action pp. 245-247

Feedback

No comments posted yet.


Post a comment





 

Please add 3 and 7 and type the answer here:

 

 

Copyright © Mike Nichols