有方法将默认查询添加到Mongo存储库吗?

huangapple go评论62阅读模式
英文:

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);

huangapple
  • 本文由 发表于 2020年9月20日 16:17:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63976928.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定