开发者

Data Binding Many-ended Associations

Assume I want to databind HTTP parameters to an instance of

class Continent {
  Integer id
  String name
  Country country
}

where the Country class looks something like:

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

If I want to bind Continent.country to an instance of Country that already exists and can be retrieved using:

interface CountryService {
  Country get(Integer countryId)
}

A simple way to do this is to define a PropertyEditor that can convert the country's ID to the correspdonding Country instance, e.g.

public class ProductTypeEditor extends PropertyEdito开发者_StackOverflowrSupport {

    CountryService countryService // set this via dependency injection

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

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

If instead I want to databind an instance of

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

and the IDs of the countries are sent in a HTTP (array parameter). Is there any easy way to bind the Collection<Country>, e.g. by defining another PropertyEditor?


PropertyEditors are only wrappers around String <-> object. You will have to do marshaling and unmarshaling of data your self. Just like you have done above for Country.

I would create a service that does

Collection<Country> getCountries(int[] id)

then use the PropertyEditor to split and use your service. I don't think you will find a better solution. You can do something like

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜