1. 程式人生 > 實用技巧 >解決Spring中使用Example無法查詢到Mongodb中的資料問題

解決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,由於此超出本文範圍,僅給出參考連結,戳這裡這裡