[英]Spring Boot + MongoDB Id query
我有一個 Spring Boot 應用程序結合 MongoDB 作為持久層。 我有以下結構:
public class Resource {
@Id
public String Id;
...
}
我也有一個 ResourceRepository:
@RepositoryRestResource(collectionResourceRel = "resources", path = "resources")
public interface ResourceRepository extends MongoRepository<Resource, String> {
Resource findById(@Param("Id")String Id);
}
我在網上發現,當您執行像http://localhost:8080/resources/這樣的 GET 請求時,在 JSON 中返回 id 屬性的一種方法是將 id 屬性更改為 Id(大寫的 i)。 事實上,如果屬性是小寫的,我不會得到一個 id 字段,但是如果我將它更改為大寫,那么我就會得到它。 出於某種原因,我需要取回 id 屬性,所以我使用了大寫的 i。 到目前為止,很好。
但是,當我嘗試執行存儲庫中包含的查詢 findById 時,出現異常:
org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property id found on app.model.Resource!
如果我將 Id 屬性更改為 id(小寫 i),我可以成功執行 /resources/search/findById?id=... GET 請求。
我嘗試創建一個帶有查詢的自定義控制器,該查詢根據給定的 id 查找並返回一個資源:
@Controller
@RequestMapping("/resource")
public class ResourceController {
@Autowired
MongoOperations mongoOperations;
@RequestMapping(value="/findById/{resourceId}/", method= RequestMethod.GET)
@ResponseBody
public Resource findByResourceId(@PathVariable("resourceId") String resourceId) {
Resource resource = mongoOperations.findOne(query(Criteria.where("Id").is(resourceId)), Resource.class,"DOJ");
}
}
但我收到同樣的錯誤:
org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property id found on app.model.Resource!
關於如何在 JSon 中顯示 id 屬性並能夠 findById 的任何想法?
嗯,我自己找到了答案。 切換回小寫 id 以便 findById 工作並將以下類添加到項目中:
@Configuration
public class SpringDataRestConfiguration extends RepositoryRestConfigurerAdapter {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.exposeIdsFor(Resource.class);
}
}
正如該方法的名稱所暗示的那樣,此配置使 Resource 類對象在 JSON 中公開其 id。
更新:如果您使用的是最新或相對最新版本的spring-boot,則RepositoryRestConfigurerAdapter
類已被棄用,java-doc建議直接使用RepositoryRestConfigurer
接口。
所以你的代碼應該是這樣的:
@Configuration
public class SpringDataRestConfiguration implements RepositoryRestConfigurer
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.