mirror of
https://github.com/querydsl/querydsl.git
synced 2026-06-16 21:01:10 +08:00
#199 added like handling for Mongodb
This commit is contained in:
parent
435aeda81e
commit
78b5f2a198
@ -241,7 +241,15 @@ public final class ExpressionUtils {
|
||||
public static Expression<String> likeToRegex(Expression<String> expr){
|
||||
// TODO : this should take the escape character into account
|
||||
if (expr instanceof Constant<?>) {
|
||||
return ConstantImpl.create(expr.toString().replace("%", ".*").replace("_", "."));
|
||||
String like = expr.toString();
|
||||
if (!like.startsWith("%") && !like.startsWith("_")) {
|
||||
like = "^" + like;
|
||||
}
|
||||
if (!like.endsWith("%") && !like.endsWith("_")) {
|
||||
like = like + "$";
|
||||
}
|
||||
like = like.replace("%", ".*").replace("_", ".");
|
||||
return ConstantImpl.create(like);
|
||||
} else if (expr instanceof Operation<?>) {
|
||||
Operation<?> o = (Operation<?>)expr;
|
||||
if (o.getOperator() == Ops.CONCAT) {
|
||||
|
||||
@ -30,6 +30,8 @@ public class ExpressionUtilsTest {
|
||||
@Test
|
||||
public void LikeToRegex() {
|
||||
assertEquals(".*", regex(ConstantImpl.create("%")));
|
||||
assertEquals("^abc.*", regex(ConstantImpl.create("abc%")));
|
||||
assertEquals(".*abc$", regex(ConstantImpl.create("%abc")));
|
||||
assertEquals(".", regex(ConstantImpl.create("_")));
|
||||
|
||||
StringPath path = new StringPath("path");
|
||||
|
||||
@ -153,6 +153,10 @@ public class MongodbSerializer implements Visitor<Object, Void> {
|
||||
} else if (op == Ops.MATCHES_IC) {
|
||||
return asDBObject(asDBKey(expr, 0), Pattern.compile(asDBValue(expr, 1).toString(), Pattern.CASE_INSENSITIVE));
|
||||
|
||||
} else if (op == Ops.LIKE) {
|
||||
String regex = ExpressionUtils.likeToRegex((Expression)expr.getArg(1)).toString();
|
||||
return asDBObject(asDBKey(expr, 0), Pattern.compile(regex));
|
||||
|
||||
} else if (op == Ops.BETWEEN) {
|
||||
BasicDBObject value = new BasicDBObject("$gte", asDBValue(expr, 1));
|
||||
value.append("$lte", asDBValue(expr, 2));
|
||||
|
||||
@ -236,6 +236,14 @@ public class MongodbQueryTest {
|
||||
|
||||
assertQuery(user.firstName.matches(".*aa.*[^i]$"), u3, u4, u1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void Like() {
|
||||
assertQuery(user.firstName.like("Jaan%"), u3, u4);
|
||||
assertQuery(user.firstName.like("jaan%"));
|
||||
|
||||
assertQuery(user.lastName.like("%unen"), u2, u1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void IsNotNull(){
|
||||
|
||||
Loading…
Reference in New Issue
Block a user