简体   繁体   中英

Configure Hibernate to escape underscores in LIKE clause using SQL Server dialect

I have a SQL SELECT query which has a LIKE clause containing an underscore, which should specifically look for an underscore, not treat it as a wildcard:

SELECT * FROM my_table WHERE name LIKE '_H9%';

I understand that I can change the actual clause to '[_]H9%' for this to work as I expect, but the problem is that this clause is being generated by Hibernate.

Is there a way to configure Hibernate to escape all underscores in all queries in this way? Failing that, is there a way to configure SQL Server (2008 in my case) to not treat underscores as wildcards?

If you're using Criteria to create the query, you can create your own expression which subclasses org.hibernate.criterion.LikeExpression, using one of the protected constructors that takes in 'Character escapeChar', and does substitution in the value for you. Assuming that '!' is a known value that won't be in any search strings (you can pick any you like, I guess), you can just do:

public class EscapingLikeExpression extends LikeExpression {
  public EscapingLikeExpression(String propertyName, String value) {
      super(propertyName, escapeString(value), '!', false);
  }

  static String escapeString(String inputString) {
    inputString = inputString.replace("_", "!_");
    return inputString;
  }

}

if there ARE no such characters (that won't appear in your search value as literals) then add the following as the first line of escapeString() to escape those too:

    inputString = inputString.replace("!", "!!");

Why can you not do a string replacement on the value? How is this being used so that this is a non-workable solution?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM