3

I am using the below Hibernate code to filter workFlowName.

crt.add(Restrictions.like("workFlowName", workFlow, MatchMode.ANYWHERE));
// crt is the criteria

The problem is when I pass the value to workFlow from web (TextBox).it fetching the value correctly (I am passing sym in text box if fetch 10 records.if i pass the same value like %sym% again it is fetching same record).

Whether the criteria will omit when it see %% as argument?

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Karthick
  • 1,943
  • 3
  • 15
  • 16

1 Answers1

1

Hibernate does not escape special chars in like (e.g. the percentage % sign). But there are descriptions how to solve it (escape it):

In general we could implement our own EscapedILikeExpression (taken from the first link above)

class EscapedILikeExpression extends IlikeExpression {
    private static final String HIBERNATE_ESCAPE_CHAR = "\\";

    public EscapedILikeExpression(String propertyName, Object value) {
        super(propertyName, value);
    }

    public EscapedILikeExpression(String propertyName, String value, MatchMode matchMode) {
        super(propertyName, replaceAll(value), matchMode);
    }

    private static String replaceAll(String value) {
        return value
                .replace("\\",  HIBERNATE_ESCAPE_CHAR + "\\")
                .replace("_",   HIBERNATE_ESCAPE_CHAR + "_")
                .replace("%",   HIBERNATE_ESCAPE_CHAR + "%");

    }
}

and

public class EscapedRestrictions {
    public static Criterion ilike(String propertyName, String value) {
        return new EscapedILikeExpression(propertyName, value);
    }

    public static Criterion ilike(String propertyName, String value, MatchMode matchMode) {
        return new EscapedILikeExpression(propertyName, value, matchMode);
    }
}

And now we should be able to call

crt.add(EscapedRestrictions.ilike("workFlowName", workFlow, MatchMode.ANYWHERE));
Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Then how it fetching the record even if pass %sym%.It should return with empty values right ? – Karthick Jun 15 '15 at 13:11
  • The point is, that if we want symbols like % to be used for filtering ... we have to escape them. With SQL Server I changed them from % into `[%]`... and then only value which contains that would be returned. I.e. if we would use [%]sym[%] with SQL server, only records with these will be found, because it will be converted into SQL statement `WHERE x like '%[%]sym[%]%'` – Radim Köhler Jun 15 '15 at 13:14
  • Thanks Radim Köhler.Now i got it . – Karthick Jun 15 '15 at 13:27
  • That's great! really. Enjoy awesome Hibernate, sir;) – Radim Köhler Jun 15 '15 at 13:28
  • Doesn't work on db2 `org.hibernate.dialect.DB2Dialect` is set – ka3ak Dec 07 '20 at 15:10