Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 266173
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T22:49:59+00:00 2026-05-11T22:49:59+00:00

For this question, we want to avoid having to write a special query since

  • 0

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 want to be able to escape special characters.

This situation is the reason for needing the ability to escape special characters:

Assume that we have table ‘foo’ in the database. Table ‘foo’ contains only 1 field, called ‘name’. The ‘name’ field can contain characters that may be considered special in a database. Two examples of such a name are ‘name_1’ and ‘name%1’. Both the ‘_’ and ‘%’ are special characters, at least in Oracle. If a user wants to search for one of these examples after they are entered in the database, problems may occur.

criterion = Restrictions.ilike("name", searchValue, MatchMode.ANYWHERE);
return findByCriteria(null, criterion);

In this code, ‘searchValue’ is the value that the user has given the application to use for its search. If the user wants to search for ‘%’, the user is going to be returned with every ‘foo’ entry in the database. This is because the ‘%’ character represents the “any number of characters” wildcard for string matching and the SQL code that hibernate produces will look like:

select * from foo where name like '%' 

Is there a way to tell hibernate to escape certain characters, or to create a workaround that is not database type specific?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T22:49:59+00:00Added an answer on May 11, 2026 at 10:49 pm

    LikeExpression’s constructors are all protected, so it’s not a viable option. Also, it has problems of its own.

    A colleague and I created a patch which works pretty well. The gist of the patch is that for the LikeExpression constructor which consumes a MatchMode, we escape the special characters. For the constructor which consumes a Character (the escape character), we assume the user escapes the special characters on their own.

    We also parameterized the escape character to ensure that it can’t corrupt the SQL query if they use something like \ or a quote character.

    package org.hibernate.criterion;
    
    import org.hibernate.Criteria;
    import org.hibernate.HibernateException;
    import org.hibernate.dialect.Dialect;
    import org.hibernate.engine.TypedValue;
    
    public class LikeExpression implements Criterion {
        private final String propertyName;
        private final String value;
        private final Character escapeChar;
    
        protected LikeExpression(
                String propertyName,
                Object value) {
            this(propertyName, value.toString(), (Character) null);
        }
    
        protected LikeExpression(
                String propertyName,
                String value,
                MatchMode matchMode) {
            this( propertyName, matchMode.toMatchString( value
                    .toString()
                    .replaceAll("!", "!!")
                    .replaceAll("%", "!%")
                    .replaceAll("_", "!_")), '!' );
        }
    
        protected LikeExpression(
                String propertyName,
                String value,
                Character escapeChar) {
            this.propertyName = propertyName;
            this.value = value;
            this.escapeChar = escapeChar;
        }
    
        public String toSqlString(
                Criteria criteria,
                CriteriaQuery criteriaQuery) throws HibernateException {
            Dialect dialect = criteriaQuery.getFactory().getDialect();
            String[] columns = criteriaQuery.getColumnsUsingProjection( criteria, propertyName );
            if ( columns.length != 1 ) {
                throw new HibernateException( "Like may only be used with single-column properties" );
            }
            String lhs = lhs(dialect, columns[0]);
            return lhs + " like ?" + ( escapeChar == null ? "" : " escape ?" );
    
        }
    
        public TypedValue[] getTypedValues(
                Criteria criteria,
                CriteriaQuery criteriaQuery) throws HibernateException {
            return new TypedValue[] {
                    criteriaQuery.getTypedValue( criteria, propertyName, typedValue(value) ),
                    criteriaQuery.getTypedValue( criteria, propertyName, escapeChar.toString() )
            };
        }
    
        protected String lhs(Dialect dialect, String column) {
            return column;
        }
    
        protected String typedValue(String value) {
            return value;
        }
    
    }
    

    If you’re wondering what the lhs and typedValue methods are for, the new IlikeExpression should answer those questions.

    package org.hibernate.criterion;
    
    import org.hibernate.dialect.Dialect;
    
    public class IlikeExpression extends LikeExpression {
    
        protected IlikeExpression(
                String propertyName,
                Object value) {
            super(propertyName, value);
        }
    
        protected IlikeExpression(
                String propertyName,
                String value,
                MatchMode matchMode) {
            super(propertyName, value, matchMode);
    
        }
    
        protected IlikeExpression(
                String propertyName,
                String value,
                Character escapeChar) {
            super(propertyName, value, escapeChar);
        }
    
        @Override
        protected String lhs(Dialect dialect, String column) {
            return dialect.getLowercaseFunction() + '(' + column + ')';
        }
    
        @Override
        protected String typedValue(String value) {
            return super.typedValue(value).toLowerCase();
        }
    
    }
    

    After this, the only thing left is to make Restrictions use these new classes:

    public static Criterion like(String propertyName, Object value) {
        return new LikeExpression(propertyName, value);
    }
    
    public static Criterion like(String propertyName, String value, MatchMode matchMode) {
        return new LikeExpression(propertyName, value, matchMode);
    }
    
    public static Criterion like(String propertyName, String value, Character escapeChar) {
        return new LikeExpression(propertyName, value, escapeChar);
    }
    
    public static Criterion ilike(String propertyName, Object value) {
        return new IlikeExpression(propertyName, value);
    }
    
    public static Criterion ilike(String propertyName, String value, MatchMode matchMode) {
        return new IlikeExpression(propertyName, value, matchMode);
    }
    
    public static Criterion ilike(String propertyName, String value, Character escapeChar) {
        return new IlikeExpression(propertyName, value, escapeChar);
    }
    

    Edit: Oh yeah. This works for Oracle. We’re not sure about other databases though.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 231k
  • Answers 231k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Use the following function like this: Image('/path/to/original.image', '1/1', '150*', './thumb.jpg');… May 13, 2026 at 2:13 am
  • Editorial Team
    Editorial Team added an answer Check you database schema to see if the field (referenced… May 13, 2026 at 2:13 am
  • Editorial Team
    Editorial Team added an answer I figured out the problem - there was a session… May 13, 2026 at 2:13 am

Related Questions

Having just wrapped up a GWT-1.5 based project, I'm taking a look at what
If you're familiar with the phrase build one to throw away, well, we seem
Hi does anyone know if there are any inbuilt classes for resolving a bound
In a Django application, I want to display a multi-level (but fixed-depth) tree of

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.