Spring数据Mongo db从文档转换为标准 [英] Spring data Mongo db Convert from Document to Criteria
问题描述
所以从 Criteria
我们有 getCriteriaObject
返回 Document
然后你可以对文档做一些操作,但是我想通过转换回 Criteria
来使用结果,我真的找不到方法.
So from a Criteria
we have getCriteriaObject
which returns Document
and then you are able to do some operations on the document, but then I wanna use the results by converting back to a Criteria
, I couldn't really find how.
当然让我们考虑具有多个运算符等的复杂Criteria
.有什么想法吗?
Of course let's take in consideration complex Criteria
with multiple operators etc. Any ideas?
推荐答案
简短回答:否
Criteria
具有 Querydsl-Like 语法,允许生成 类型安全 查询.从 Document
读取可能会引入 MongoDB 与当前 MongoDB 版本不兼容的命令或语法.
Short answer: No
Criteria
has Querydsl-Like syntax which allows the generation of type-safe queries. Reading from Document
may introduce MongoDB incompatible commands or syntax for the current MongoDB version.
我们可以使用 Java 反射实现walkarounda> 将文档 key:value
添加到 Criteria private
字段中.
警告:您假设您的 Document
具有语法正确的兼容运算符.
We can implement walkaround with Java reflection to add Document key:value
into Criteria private
fields.
Warning: You assume your Document
has compatible operators with correct syntax.
将此辅助方法添加到您的类中(源):
Add this helper method into your class (souce):
public static Criteria from(Document document) {
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);
for (Entry<String, Object> set : document.entrySet()) {
criteria.put(set.getKey(), set.getValue());
}
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;
}
<小时>
现在为 Document
中的 Criteria
创建新实例:
Now create new instance for Criteria
from Document
:
Criteria newCriteria = from(criteria.getCriteriaObject());
//You have full-compatible Criteria instance
newCriteria.and("foobar").elemMatch(Criteria.where("field").is("value"));
这篇关于Spring数据Mongo db从文档转换为标准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!