解決Spring中使用Example無法查詢到Mongodb中的資料問題
阿新 • • 發佈:2020-12-11
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
,由於此超出本文範圍,僅給出參考連結,戳這裡或這裡。