問題描述
是否有可能使用 Spring Data MongoDb 來定義自定義標準? (Is possibility using Spring Data MongoDb to define custom Criteria?)
我有一個方法的簡單接口:
Criteria toCriteria(String key, String value)
接下來我想要下一個實現
public class EqExpression implements Expression
{
@Override
public Criteria toCriteria(String key, String value)
{
return Criteria.where(key).eq(Pattern.compile(value));
}
}
}
但是沒有$eq 運算符。所以我的問題是:
- 為什麼
org.springframework.data.mongodb.core.query.Criteria
沒有這樣的操作符? 有沒有辦法實現自定義 Criteria 實現或有任何解決方法?
對我來說,最好有類似
@Override public Criteria toCriteria(String key, String value) { //return new BasicDBObject(key, new BasicDBObject("$eq", value)) converted to Criteria }
的代碼
總的來說,我的目的是實現rest查詢語言,對於像gt
、lt
這樣的每個操作,我都有Expression<的具體實現
參考解法
方法 1:
using this answer, I was able to create simple $eq Criteria
private Criteria getEqCriteria(String value)
{
// hack Criteria, because new Criteria().is(value) not working!
Criteria c = new Criteria();
try
{
Field _criteria = c.getClass().getDeclaredField("criteria");
_criteria.setAccessible(true);
@SuppressWarnings("unchecked")
LinkedHashMap<String, Object> criteria = (LinkedHashMap<String, Object>) _criteria.get(c);
criteria.put("$eq", value);
Field _criteriaChain = c.getClass().getDeclaredField("criteriaChain");
_criteriaChain.setAccessible(true);
@SuppressWarnings("unchecked")
List<Criteria> criteriaChain = (List<Criteria>) _criteriaChain.get(c);
criteriaChain.add(c);
} catch (Exception e)
{
// Ignore
}
return c;
}
(by Roman Grytsyshyn、Daulet)
參考文件