For this question, we want to avoid having to write a special query since the query would have to be different across multiple databases. Using only hibernate criteria, we w
If you use Hibernate 3.2+, you can subclass LikeExpression, and then create factory like/ilike methods:
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.LikeExpression;
import org.hibernate.criterion.MatchMode;
public class EscapedLikeRestrictions {
private EscapedLikeRestrictions() {}
public static Criterion likeEscaped(String propertyName, String value, MatchMode matchMode) {
return likeEscaped(propertyName, value, matchMode, false);
}
public static Criterion ilikeEscaped(String propertyName, String value, MatchMode matchMode) {
return likeEscaped(propertyName, value, matchMode, true);
}
private static Criterion likeEscaped(String propertyName, String value, MatchMode matchMode, boolean ignoreCase) {
return new LikeExpression(propertyName, escape(value), matchMode, '!', ignoreCase) {/*a trick to call protected constructor*/};
}
private static String escape(String value) {
return value
.replace("!", "!!")
.replace("%", "!%")
.replace("_", "!_");
}
}