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

4次阅读

共计 656 个字符,预计需要花费 2 分钟才能阅读完成。

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

正文完
 0