我正在尝试将Play 2.3.x用于一个小项目。我习惯于1.2.x,并且正在努力理解一些变化。
其中一个变化是使用EBeans和表单。这在1.2.x中非常有效,但我不太了解如何在2.3.x中完成此操作
我有控制器:
package controllers;
import models.Device;
import play.data.DynamicForm;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import java.util.List;
public class Devices extends Controller {
public static Result index() {
List<Device> devices = Device.find.all();
return ok(views.html.Devices.index.render(devices));
}
public static Result add () {
Form<Device> myForm = Form.form(Device.class);
return ok(views.html.Devices.add.render(myForm));
}
public static Result edit(Long id){
Device device = Device.find.byId(id);
Form<Device> myForm = Form.form(Device.class);
myForm = myForm.fill(device);
return ok(views.html.Devices.edit.render(myForm));
}
public static Result update() {
Device device = Form.form(Device.class).bindFromRequest().get();
device.update();
return index();
}
}
我可以添加设备,并想要编辑它。这是模板:
@(myForm: Form[Device])
@main("Edit a device") {
@helper.form(action = routes.Devices.update()) {
@helper.inputText(myForm("name"))
@helper.inputText(myForm("ipAddress"))
<input type="submit" value="Submit">
}
<a href="@routes.Devices.index()">Cancel</a>
}
但是如何将更改与已存储的对象合并?有没有简单的方法,或者我是否找到了对象然后手动逐个字段地遍历对象?在1.2.x(使用JPA)中,有merge()选项可以处理所有这些。我会使用JPA,但1.2.x中的默认支持似乎不那么强大。
现在我得到(可以理解):
[OptimisticLockException: Data has changed. updated [0] rows sql[update device set name=?, ip_address=?, last_update=? where id=?] bind[null]]
答案 0 :(得分:0)
这种乐观锁定是由于您的表单中缺少id
值而造成的,您在编辑表单中处于良好的ID状态:
<input type="hidden" value="@myForm("id")">
无论如何正确的代码是:
<input type="hidden" name="id" value="@myForm("id").value">
两个提示:
id
的{{1}}为空。正确地说它可以是这样的,最后也看到如何在成功更新后重定向到索引:
device
public static Result update() {
Form<Device> deviceForm = Form.form(Device.class).bindFromRequest();
if (deviceForm.hasErrors()) {
return badRequest(views.html.Devices.edit.render(deviceForm, listOfRoles()));
}
// Form is OK, has no errors, we can proceed
Device device = deviceForm.get();
device.update(device.id);
return redirect(routes.Devices.index());
}
只是来自listOfRoles()
操作的代码:
edit()