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