小编Sil*_*las的帖子

在Spring RestController中实现RequestMethod.PATCH

我正在使用MongoRepository为MongoDB数据库创建Rest API.我想创建一个使用"RequestMethod.PATCH"的端点并实现"PATCH"功能:使用@RequestBody中提供的字段进行增量更新.

通过在我的Repository类上使用"@RepositoryRestResource"注释,我想要的功能已存在于"Spring Data Rest"中,如此处所述https://spring.io/guides/gs/accessing-data-rest/

但我不想像那样公开我的Repository类.我喜欢经典的Controller-> Service-> Repository lineage.我的控制器看起来像这样:

@RestController
public class ActivitiesController {

    @Autowired
    ActivitiesService activitiesService;

    @RequestMapping(value="activities", method=RequestMethod.PATCH)
    public ActivityModel updateActivity(
            @RequestBody ActivityModel activityModel
    ){
        //Input ActivityModel will only have subset of fields that have been changed, aka the delta
        return activitiesService.update(activityModel);
    }

    @RequestMapping(value="activities", method=RequestMethod.PUT)
    public ActivityModel updateActivity(
            @RequestBody ActivityModel activityModel
    ){
        //Input ActivityModel will have all fields populated
        return activitiesService.save(activityModel);
    }

}
Run Code Online (Sandbox Code Playgroud)

我的存储库在这里:

@Repository
public interface ActivitiesRepo extends MongoRepository<ActivityModel, String> {
    //out of the box implementation
} …
Run Code Online (Sandbox Code Playgroud)

mongodb spring-data-rest spring-boot spring-restcontroller

5
推荐指数
0
解决办法
991
查看次数