Spring Boot中使用MongoDB中的Example查询数据时查询不到,示例代码如下:

ExampleMatcher matcher = ExampleMatcher.matching()
.withMatcher("username", ExampleMatcher.GenericPropertyMatchers.exact())
.withIgnorePaths("id","password");

2 问题分析

Spring Data中使用MongoDB时,插入数据会添加一个_class字段,这个字段是用来映射POJO的,也就是说,如果一个实体类如下:

@Document(collection = "user")
class User{
	@Id
	private String id;
	private String username;
	private String password;
}

则存进数据库的字段如下:

_id,_class,username,password

而使用ExampleMatcher,默认情况下会匹配所有字段,因此,如果实体类的包名改变了,_class字段就不会匹配,这样就无法正确地得到查询结果。

3 解决方案

_class添加进IgnorePath即可:

.withIgnorePaths("_class","id","password")

如果不想在插入数据时自动添加_class字段,可以修改MongoTemplate或者MappingMongoConverter,由于此超出本文范围,仅给出参考链接,戳这里这里

相关文章:

  • 2022-01-21
  • 2021-09-22
  • 2021-06-21
  • 2021-10-26
  • 2022-01-23
  • 2022-12-23
猜你喜欢
  • 2021-05-26
  • 2021-05-26
  • 2022-12-23
  • 2021-10-18
  • 2021-05-16
  • 2021-07-14
  • 2021-11-25
相关资源
相似解决方案