2011-07-05 37 views
1

假設我想數據綁定HTTP參數的數據綁定許多端關聯

一個實例,其中Country類看起來是這樣的:

class Country { 
    Integer id 
    String name 
    Currency currency 
    // other properties 
} 

如果我要綁定Continent.countryCountry已經存在並且可以使用的實例:

interface CountryService { 
    Country get(Integer countryId) 
} 

這樣做的一個簡單方法是定義一個PropertyEditor,它可以將國家的ID轉換爲相應的Country實例。

public class ProductTypeEditor extends PropertyEditorSupport { 

    CountryService countryService // set this via dependency injection 

    void setAsText(String paramValue) { 
     if (paramValue) 
      value = countryService.get(paramValue.toInteger()) 
    } 

    public String getAsText() { 
     value?.id.toString() 
    } 
} 

相反,如果我想數據綁定的

class Continent { 
    Integer id 
    String name 
    Collection<Country> countries 
} 

的實例和國家的ID在HTTP(數組參數)被髮送。有沒有簡單的方法來綁定Collection<Country>,例如通過定義另一個PropertyEditor

+0

你爲什麼要綁定到Collection 而不是Continent?我想你會想要綁定到大陸的ID而不是國家的名單?對? –

+0

爲了本示例的目的,您可以假設用戶可以創建新的大陸,但各大洲可能只包含已創建的國家/地區。 –

+0

難道你不能用逗號分開國家代碼並加載每一個嗎?如果每一個緩存或您使用一個很好的單行SQL語句,那麼你應該能夠加載所有在一個請求?或者你在哪裏尋找更容易的東西? –

回答

0

PropertyEditors只是字符串< - >對象的包裝。你將不得不對你自己的數據進行編組和解組。就像你以上爲國家做的一樣。

我會創建一個具有

Collection<Country> getCountries(int[] id)

然後使用屬性編輯拆分和使用你的服務的服務。我認爲你不會找到更好的解決方案。你可以做類似

void setAsText(String paramValue) { 
     ids = param.split(",") 
     // make each id an int 
     value = service.getCountries(ids) 
    }