java - 无法使用 JpaRepository 解析 SpringMVC 中的 ResponseEntity

标签 java rest spring-mvc spring-data-jpa

这是我的 Controller :

package com.hodor.booking.controller;

import com.hodor.booking.jpa.domain.Vehicle;
import com.hodor.booking.service.VehicleService;
import com.wordnik.swagger.annotations.Api;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/v1/vehicles")
@Api(value = "vehicles", description = "Vehicle resource endpoint")

public class VehicleController {

    private static final Logger log = LoggerFactory.getLogger(VehicleController.class);

    @Autowired
    private VehicleService vehicleService;

    @RequestMapping(method = RequestMethod.GET)
    public List<Vehicle> index() {
        log.debug("Getting all vehicles");
        return vehicleService.findAll();
    }

    @RequestMapping(value="/save", method=RequestMethod.POST, consumes="application/json")

    @ResponseBody
    public Vehicle setVehicle(@RequestBody Vehicle vehicle) {
        log.debug("Inserting vehicle");

        if (vehicle.getLicensePlate() == null){
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
        }

        return vehicleService.saveVehicle(vehicle);
    }
}

我想在上面的 If-Guard 中实现的是,如果车辆对象没有 LicensePlate 成员,则发回相应的 HTTP 状态 header 冲突或其他内容。

我来自 Node 和 Express 背景,我习惯于设置 header 、发送响应并完成它。然而在这种情况下(JPA)它似乎不起作用。有什么想法吗?

最佳答案

一种替代方法是利用 Spring 的验证支持来声明性地添加 POJO 的验证。基本上,您可以向 Vehicle 类添加注释,例如:

public class Vehicle {
    @NotNull
    private LicensePlate licensePlate;

    // getters, setters
}

然后将 @Valid 注释添加到 Controller 方法中:

@ResponseBody
public Vehicle setVehicle(@RequestBody @Valid Vehicle vehicle) {
    log.debug("Inserting vehicle");
    return vehicleService.saveVehicle(vehicle);
}

如果验证失败,Spring将返回400响应。

确保您的类路径上有 JSR-303/JSR-349 Bean Validation 实现,例如 Hibernate Validator(它可以在没有 Hibernate ORM 支持的情况下使用)。

更多信息可以在validation chapter中找到Spring 引用文档。

关于java - 无法使用 JpaRepository 解析 SpringMVC 中的 ResponseEntity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37036460/

相关文章:

json - 如何让 Invoke-RestMethod 按原样打印响应正文

java - Spring 和 Jackson Json : serialising two different sets of fields

hibernate - 使用 Hibernate 为用户实现 EAV 模式 -> 设置关系

java - Spring 启动 : "No qualifying bean of type... found" when autowiring concrete class

java - 通用编写器/输出器。 Reader 之于 Iterator,Writer 之于 X?

java - 从字符串中删除随机字符

java - linux上的tcp java连接速率限制

java - 多个构造函数和 if 语句

java - Spring MVC,将@ExceptionHandler 迁移到 HandlerExceptionResolver 以获得 RESTful 服务

rest - 我如何告诉我的前端后台作业已使用 Web 套接字完成?