【问题标题】:How do you update a single table column in spring boot without updating the rest of the attributes?如何在 Spring Boot 中更新单个表列而不更新其余属性?
【发布时间】:2020-05-10 00:11:28
【问题描述】:

我正在使用 spring boot 开发汽车销售系统。当汽车经销商发布待售汽车时,汽车状态默认设置为待处理,管理员应批准该帖子。我想更新此汽车状态而不更新汽车的其他属性(里程、价格、型号等)。因此,我尝试使用 put,但出现不允许 POST 的错误。到目前为止,这是我的代码。我的代码使用@PathVariable 获取的类似于 mysql 语句 set columnName = newValue where id = id 的任何见解。

产品存储库(用于更新单个列)

@Modifying
@Query(value = "update Product p set p.status = :status where  p.carId= :carId")
void setUpdateStatus (@Param("status") String status, @Param("carId") Long carId); 

产品服务更新状态的方法。

   public void updateStatus( Long carId){
   productRepository.setUpdateStatus("APPROVED",carId);
   }

控制器方法使用 @PathVariable 从视图 url 获取产品 ID。

@PutMapping("/updateStatus/{carId}")
public void updateStatus(@PathVariable("carId") Long carId){
    productService.updateStatus(carId);

}

这是我的 thymeleaf 视图部分,负责我从中获取 id 的 url。

<form action="#" th:action="@{'/updateStatus/'+${pending.carId}}" th:method="put" >
                <input type="hidden" name="_method" value="put" />
                <button type="submit" id="Approve" name="Approve"> </button>
 </form>

我希望 id 用于将状态更新为 APPROVED。但我收到错误 mehtod POST not allowed。从上面可以看出,我的方法 =“put”不是 POST。我不知道出了什么问题。

【问题讨论】:

    标签: java spring-boot spring-mvc spring-data-jpa thymeleaf


    【解决方案1】:

    可能你的项目中开启了spring security,使用spring security时默认开启csrf保护,所以需要在request header中发送csrf参数或者关闭csrf。

    这里可以看到如何发送header参数:Spring MVC PUT Request returns 405 Method Not Allowed

    以及如何停用 csrf: Enable HTTP Request POST in Spring Boot

    仅将第二个选项用于开发!您可以使您的应用程序不安全,停用 crsf 保护。

    【讨论】:

    • 我使用 POST 解决了这个问题。 PUT 方法在 html 中是 NOT 允许的。我使用http.crsf().disabled 禁用了csrf,但这并没有帮助。设置方法=“POST”解决了我的问题
    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 2020-11-15
    相关资源
    最近更新 更多