英文:
Is there way to add default query to mongo repository?
问题
有一个名为Person的类:
public class Person{
private String name;
private boolean active;
}
当我调用personRepository.findByName("John Doe")时,结果应该是名为John Doe且active为True的对象。同时,当调用personRepository.findByNameAndActive("John Doe", false)时,应该返回所有名为John Doe且active为false的对象的结果。
有没有方法可以实现这个?
英文:
Say, we have a class named person
public class Person{
private String name;
private boolean active;
}
When I call personRepository.findByName("John Doe") the result should be the objects with the name John Doe and active is True. Meanwhile, when personRepository.findByNameAndActive("John Doe", false), it should return the result of all the objects with John Doe and active = false
Is there any way to do this ?
答案1
得分: 0
很不幸的是,默认的 *MongoRepository* 方法不支持 **OR** 或 **AND** 子句。
[支持的查询方法关键字][1]
[1]: https://i.stack.imgur.com/RUoDe.png
但是您可以使用 **@Query** 注解来定义该方法应该执行的操作:
```lang-java
@Query("{ 'name' : ?0, 'active' : true }")
Person findByName(String name);
@Query("{ 'name' : ?0, 'active' : ?1 }")
Person findByNameAndActive(String name, boolean active);
英文:
Unfortunately, default MongoRepository methods do not support OR or AND clauses.
Supported keywords for query methods
But you can use a @Query annotation to define what should be done by this method:
@Query("{ 'name' : ?0, 'active' : true }")
Person findByName(String name);
@Query("{ 'name' : ?0, 'active' : ?1 }")
Person findByNameAndActive(String name, boolean active);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论