弹簧支架控制器复合主键

时间:2015-11-11 16:21:35

标签: spring rest controller spring-boot

我有一个带有复合主键的简单spring-data / jpa对象:

@Entity
@Table(name = "position")
public class Position implements Serializable {

    @EmbeddedId
    private PositionId positionId;

    @Column(name="heading")
    private Double heading;
...

@Embeddable
public class PositionId implements Serializable {
    private String hexIdent;
    @Temporal(TemporalType.TIMESTAMP)
    private Date timestamp;
...

我试图创建一个REST控制器来创建一个Position对象。我的控制器创建方法如下:

@RequestMapping(method=POST,
    consumes=APPLICATION_JSON_VALUE,
    produces=APPLICATION_JSON_VALUE)
public ResponseEntity<Position> createPosition(@RequestBody Position newPosition) {
    Position position = positionService.create(newPosition);
    return ResponseEntity.ok().body(position);
}

和我发送的json看起来像:

{
"positionId":{"hexIdent":"abc123","timestamp":"Tue Nov 10 15:20:43 MST 2015"},
"verticalRate":3.2,
"heading":90.2,
"groundSpeed":123.2,
"lon":25.2,
"lat":25.2
}

当执行服务时,它无法从传入的JSON解析PostionId(NPE)(REST服务在方法调用中创建的positionId为null,它实际上在positionId的hashCode()调用上失败)< / p>

这是对服务的测试:

@Test
public void testCreatePosition() throws Exception {
    JSONObject p003Id = new JSONObject();
    p003Id.put("hexIdent", "abc123");
    //p003Id.put("timestamp", new Date());
    JSONObject p003 = new JSONObject();
    p003.put("positionId", p003Id);
    p003.put("lat", 25.2D);
    p003.put("lon", 25.2D);
    p003.put("heading", 90.2D);
    p003.put("groundSpeed", 123.2D);
    p003.put("verticalRate", 3.2D);
    String jsonString = p003.toString();

    given().
        contentType("application/json").
        body(jsonString).
    when().
        post("/position").
    then().
        statusCode(HttpStatus.SC_OK).
        contentType(ContentType.JSON).
        body("hexIdent", equalTo("abc123")).
        body("lat", equalTo(25.2D)).
        body("lon", equalTo(25.2D));
}

在spring-data / jpa中定义复合主键或在弹簧控制器中处理复合主键是否有技巧?我的json错了吗?

1 个答案:

答案 0 :(得分:0)

想出来。我的Position()类缺少positionId的setter。不知怎的,我错过了那个。无论如何,使用 all 典型的预期getter和setter,它现在反序列化了。