Using hibernate criteria, is there a way to escape special characters?

前端 未结 5 1105
天涯浪人
天涯浪人 2020-12-03 03:19

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

5条回答
  •  一向
    一向 (楼主)
    2020-12-03 04:08

    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("_", "!_");
        }
    }
    

提交回复
热议问题