我正在尝试将Play 2.3.x用于一个小项目。我已经习惯了 1.2.x,并且正在努力理解一些变化。
其中一个变化是使用电子模型和表单。这在 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]]
在您的情况下,此乐观锁定是由于表单中缺少id
值引起的,您在编辑表单中使用 id 处于良好轨道上:
<input type="hidden" value="@myForm("id")">
无论如何,正确的代码是:
<input type="hidden" name="id" value="@myForm("id").value">
两个提示:
- 您可以在 Idea 中设置断点 - 因此在调试模式下,您可以识别出绑定
device
的id
为空。 - 在对字段使用约束时,还应处理操作中的错误
正确地,它可以是这样的,还可以在最后看到如何在成功更新后重定向到索引:
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()
操作中包装的代码:
private static List<String> listOfRoles(){
List<String> list = new ArrayList<String>();
for(DeviceRole role : DeviceRole.values()) {
list.add(role.toString());
}
return list;
}