2012年3月21日 星期三

entity converter Value is not a valid 問題

問題描述:

在一個查詢頁,有 select 、button ,
select 項目用 做 view 和 controller 的值轉換。
範例如下:



但是在網頁很久沒有動作後,再去改變下拉選單的內容,會出現 Value is not a valid 錯誤訊息。

參考網路上說明後,推測是因為 過很久再去點選畫面時,view 經由entity converter 傳成的物件和 emtityManager 重新 query 的list 在比較時,發現沒有符合。所以認為選擇的值是 Value is not a valid 。

解決方法:overwrite equals 方法。 真是夠簡單的。

The scenario

JSF runs the converter and loads the entity from the persistence context; JSF runs any validators, and adds it's own - that the selected object must be in the original list; the validation fails as a new object has been loaded from the persistence context.

The solution

You've got two options:

Ensure that you are in a long-running conversation that spans the both the select list creation and the submission of the form.
Use key equality rather than object equality (make equals return true if both objects have the same natural or business key). It's important to note that basing equality on surrogate key identity isn't recommended. You can read more here
Which approach should you take? The second solution is the simplest to understand but sometimes it is hard (or not possible) to define a natural key so you'll need to use the first solution.
參考來源