繁体   English   中英

Spring Boot + MongoDB Id 查询

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM