Blog Stats
  • Posts - 62
  • Articles - 1
  • Comments - 56
  • Trackbacks - 40

 

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
    • Share This Post:
    • Share on Twitter
    • Share on Facebook
    • Share on Technorati

Feedback

# NHibernate

Gravatar If the innerException parameter is not a null reference, the current exception is raised. - car title loans irvine 1/11/2012 1:26 PM | Car title loans irvine

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

 

 

Copyright © Mike Nichols