休眠标准接受%%的值 [英] Hibernate criteria accepting %% value
问题描述
我正在使用下面的Hibernate代码来过滤workFlowName
.
I am using the below Hibernate code to filter workFlowName
.
crt.add(Restrictions.like("workFlowName", workFlow, MatchMode.ANYWHERE));
// crt is the criteria
问题是当我从Web(TextBox)将值传递给 workFlow 时,它正确地获取了值(如果获取,我将在文本框中传递 sym
10条记录.如果我再次传递相同的值,例如 %sym%
,它将获取相同的记录).
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?
推荐答案
Hibernate不会以 like 的形式转义特殊字符(例如,百分比 %
).但是有描述如何解决它(逃避它):
Hibernate does not escape special chars in like (e.g. the percentage %
sign). But there are descriptions how to solve it (escape it):
- Escaping special characters in Hibernate queries
- Using hibernate criteria, is there a way to escape special characters?
- Escape special characters in hibernate criteria
通常,我们可以实现自己的 EscapedILikeExpression
(摘自上面的第一个链接)
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 + "%");
}
}
和
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));
这篇关于休眠标准接受%%的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!