当更新未在 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);
}
但这也无济于事。秘诀是什么?