2015-01-07 39 views
0

我正在嘗試將Play 2.3.x用於小型項目。我習慣於1.2.x,並且正在努力理解一些變化。與Bean合併並播放Java的最佳方式

其中一個變化是使用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

發佈項目到GitHub上請,我會檢查它(只是假設這是一般測試項目w /出證書) – biesior

+0

我發佈它在https://github.com/luukjansen/temperaturecontrol。 –

+0

(有問題的表單是http:// localhost:9000/devices /其中可以添加一個) –

回答

0

這種樂觀鎖在你的情況下,在您的形式缺少id值造成的,你在編輯形式良好的跟蹤與ID:

<input type="hidden" value="@myForm("id")"> 

反正正確的代碼是:

<input type="hidden" name="id" value="@myForm("id").value"> 

兩個小技巧:

  1. 您可以在Idea中設置斷點 - 因此在調試模式下,您可以識別出綁定的deviceid爲空。
  2. 在使用你的領域限制,你也應該在你的行動處理錯誤

正確也可以是這樣的事情,也看到到底如何重定向到成功更新之後的指數:

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; 
} 
+0

這很完美!現在,枚舉,因爲它會導致「無效的屬性」角色[0]'「,但我把它作爲一個不同的問題發佈。 –

+0

我建議使用ManyToMany關係 – biesior