【问题标题】:Change only 1 Parameter with PutRequest?使用 PutRequest 仅更改 1 个参数?
【发布时间】:2020-04-24 23:03:41
【问题描述】:

我有一个问题。是否可以仅更改 PutRequest 中的一个参数? 我在互联网上没有找到任何关于此的内容。

    @GetMapping("/templates/{user_name}/{template_id}")
    public Template retrieveTemplate(@PathVariable("user_name") String user_name,@PathVariable("template_id") int template_id)
    {
        return templateRepository.findByTemplateIdAndUserName(template_id, user_name);

    }

这是我的 GetRequest,我希望只能更改参数模板。

【问题讨论】:

  • 你能改进你的问题吗?我不确定你到底想做什么。
  • 好吧,对不起。它有一个名为 Templates 的数据库。在这个数据库中有参数 id、user_name、template_id 和一个字符串模板。当我启动 PutRequest 时,不应允许我更改 id template_id 和 user_name。只有模板应该可以更改。
  • 您需要的是 HTTP 中的 PATCH。

标签: java microservices


【解决方案1】:

正如 Tom 已经提到的,如果您只想部分更新现有实体,那么您必须使用 PATCH HTTP 动词。您可以在this answer 找到更多信息。

这里还有a small guide告诉这两种方法的区别。

最后,可以帮助您的代码 sn-p 将是:

@PatchMapping("/templates/{user_name}/{template_id}")
public Template updateTemplate(@PathVariable("user_name") String user_name, 
                               @PathVariable("template_id") int template_id, 
                               @RequestBody Template template)  {
    return templateService.updateTemplate(template_id, template);
}

@Service
public static class TemplateService {

    @Autowired
    private TemplateRepository templateRepository;

    @Transactional
    public Template updateTemplate(int id, Template updateTemplate) {
        Template foundTemplate = templateRepository.findById(id);
        foundTemplate.setTemplate(updateTemplate.getTemplate());
        return foundTemplate;
    }
}

【讨论】:

  • @Doncarlito87,很高兴它对您有所帮助!请您将我的答案标记为正确的吗?
  • 我愿意,但我的声望不超过 15 个。所以 Stack Over Flow 不允许我这样做。对不起。
  • 啊,那没问题 :) 编码愉快!
猜你喜欢
  • 2015-03-21
  • 1970-01-01
  • 2021-01-22
  • 1970-01-01
  • 2013-08-02
  • 2017-01-18
  • 1970-01-01
  • 2017-11-10
  • 1970-01-01
相关资源
最近更新 更多