0

当更新未在 JSON 请求中指定必填字段时,我试图让 Play 停止抱怨。必填字段已经具有我不想更改的值,因此我不必再次指定它们。

精简模型:

@Entity
public class Run extends Model {
    public enum Status { RUNNING, OK, WARNINGS, ERRORS, FAILED, CERTIFIED };

    @Id
    public Long id;

    @Constraints.Required
    @ManyToOne(cascade = CascadeType.REFRESH)
    public Task task;

    @JodaDateTime
    @Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")
    public DateTime started;
    @JodaDateTime
    @Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")
    public DateTime completed;

    @Enumerated(EnumType.STRING)
    @Column(columnDefinition="ENUM('OK','WARNINGS','ERRORS','RUNNING','FAILED','CERTIFIED')")
    public Status result;

}

基于示例应用程序之一,我的初始控制器操作是:

@Transactional
@BodyParser.Of(play.mvc.BodyParser.Json.class)
public static Result update(Long run_id) {
    Form<Run> runForm = form(Run.class).bindFromRequest();
    if(runForm.hasErrors()) {
        return badRequest(runForm.errorsAsJson());
    }
    runForm.get().update(run_id);

    ObjectNode result = Json.newObject();
    result.put("id", run_id);

    return ok(result);
}

但如果我只是发送{ completed: '1341268791000', result: 'ERRORS }它抱怨这task是必需的。

然后我想也许我可以用Form.fill它来修复它:

@Transactional
@BodyParser.Of(play.mvc.BodyParser.Json.class)
public static Result update(Long run_id) {
    Run run = Run.find.byId(run_id);
    Form<Run> runForm = form(Run.class).fill(run).bind(request().body().asJson());

    if (runForm.hasErrors())
        return badRequest(runForm.errorsAsJson());

    runForm.get().update(run_id);

    ObjectNode result = Json.newObject();
    result.put("id", run_id);

    return ok(result);
}

但这也无济于事。秘诀是什么?

4

1 回答 1

0

您不需要使用 Form 插入/更新任何字段,您也可以“手动”更新字段(简化示例,当然在您的示例中,您需要从 Json 中提取 someField

public static Result update(Long run_id) {
    Run run = Run.find.byId(run_id);
    run.someField = form().bindFromRequest().get("someField");
    run.update();
    return ok();
}
于 2012-07-02T23:41:03.380 回答