使用 mongoTemplate.find(query, Entity.class) 並加入 query.with(new Sort(Direction.DESC, "downloadCount.china")) 時,拋出 IllegalAccessError 及 PropertyReferenceException,提示找不到 downloadCount.china 路徑。
實體類中 downloadCount 宣告為 JSONObject(或 Map),而非具體的內部類。Spring Data MongoDB 依靠實體類的屬性結構建立欄位映射,無法解析 JSONObject 內部的 china 鍵。
public class MyEntity {
@Id
private String id;
// 改為內部類,而非 JSONObject
private DownloadCount downloadCount;
// Getter/Setter
public static class DownloadCount {
private int china;
private int google;
// Getter/Setter
}
}
修改後,Sort(Direction.DESC, "downloadCount.china") 及 Criteria.where("downloadCount.china").is(10) 均可正常運作。
MappingMongoConverter 依據實體類結構進行欄位路徑解析。JSONObject 或 Map 被視為「不透明物件」,無法深入其鍵值結構。PropertyPath 能正確建立 downloadCount.china 路徑。Map 或 Document。logging.level.org.springframework.data.mongodb=DEBUG 可提前發現映射警告。