4.2.2.3.3. Пример специализированного Datatype
Рассмотрим реализацию нестандартного типа GeoCoordinateDatatype, предназначенного для атрибутов, хранящих географические координаты.
Создаем класс в модуле global:
public class GeoCoordinateDatatype extends DoubleDatatype {
public static final String NAME = "geocoordinate";
// the format is the same for all locales but may differ in decimal points
public static final String FORMAT = "#0.000000";
public GeoCoordinateDatatype(Element element) {
super(element);
}
@Override
public String getName() {
return NAME;
}
@Override
public String format(Double value, Locale locale) {
if (value == null)
return "";
FormatStrings formatStrings = Datatypes.getFormatStrings(locale);
if (formatStrings == null)
return format(value); // FormatStrings are not defined for locales, so formatting is made according to datatypes.xml file
NumberFormat format = new DecimalFormat(FORMAT, formatStrings.getFormatSymbols());
return format.format(value);
}
@Override
public Double parse(String value, Locale locale) throws ParseException {
if (StringUtils.isBlank(value))
return null;
FormatStrings formatStrings = Datatypes.getFormatStrings(locale);
if (formatStrings == null)
return parse(value); // FormatStrings are not defined for locales, so parsing is made according to datatypes.xml file
NumberFormat format = new DecimalFormat(FORMAT, formatStrings.getFormatSymbols());
return parse(value, format).doubleValue();
}
}
Создаем файл datatypes.xml
в корне каталога src
модуля global проекта приложения и копируем в него все из файла /com/haulmont/chile/core/datatypes/datatypes.xml
, расположенного в модуле global базового проекта cuba. Затем добавляем в него регистрацию нового типа:
<datatypes>
<datatype class="com.sample.sales.entity.GeoCoordinateDatatype"
format="#0.000000" decimalSeparator="." groupingSeparator=""/>
...
Указываем новый тип данных для требуемых атрибутов:
@MetaProperty(datatype = GeoCoordinateDatatype.NAME)
@Column(name = "LATITUDE")
private Double latitude;
После выполнения перечисленных действий атрибут latitude
везде в приложении будет отображаться в нужном формате.