关于spring-data-jpa:解决Spring中使用Example无法查询到Mongodb中的数据问题

1 问题形容

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,因为此超出本文范畴,仅给出参考链接,戳这里或这里。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理