【问题标题】:spring rest controller composite primary keyspring rest控制器复合主键
【发布时间】:2015-11-11 16:21:35
【问题描述】:

我有一个带有复合主键的简单 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()调用上失败)

这是服务的测试:

@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 中定义复合主键或在 spring rest 控制器中处理它是否有技巧?我的json错了吗?

【问题讨论】:

  • 您能添加更多信息,例如堆栈跟踪吗?

标签: spring rest controller spring-boot


【解决方案1】:

想通了。我的 Position() 类缺少 positionId 的设置器。不知何故,我错过了生成它。无论如何,使用 all 典型的预期 getter 和 setter 现在反序列化就好了。

【讨论】:

    猜你喜欢
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 2013-06-02
    • 1970-01-01
    • 2014-03-18
    相关资源
    最近更新 更多