在表中以不同方式格式化相同类型的两个实体字段

时间:2015-11-04 11:18:34

标签: java jpa vaadin vaadin7 gregorian-calendar

我正在使用带有实体类的JPA容器来填充MySQL中的表。 其中两个字段是GregorianCalendar字段(一个是日期,一个是时间),我正在寻找一种方法来单独格式化/转换它们,以便日期显示为短日期(例如dd-MM-yyyy),时间出现根据现场短24小时(HH:mm)。

根据我的搜索结果,我了解格式化日期和时间的最佳方法是覆盖默认表,这就是我所做的:

final Table opTable = new Table() {

            private static final long serialVersionUID = 1L;

            @Override
            protected String formatPropertyValue(Object rowId, Object colId, Property property) {

                Object v = property.getValue();

                if (v instanceof GregorianCalendar) {
                    GregorianCalendar datez = (GregorianCalendar) v;
                    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMANY);
                    String formattedDate = df.format(datez.getTime());
                    return formattedDate;
                }

                if (v instanceof GregorianCalendar) {
                    GregorianCalendar timeValue = (GregorianCalendar) v;
                    SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss");
                    fmt.setCalendar(timeValue);
                    String timeFormatted = fmt.format(timeValue.getTime());
                    return timeFormatted;
                }

                return super.formatPropertyValue(rowId, colId, property);
            }

        };

填充表格:

bookings = JPAContainerFactory.make(BookingEntity.class, CSAdminUI.PERSISTENCE_UNIT);
opTable = new Table(null, bookings); opTable.setContainerDataSource(bookings);
opTable.setVisibleColumns(new Object[] { "operator.rowid", "activity.name", "startDate", "startTime", "done", "price", "operatorCost", "paymentType", "voucherCode", "hints", "timeLeft", "succeded", "teamPicture", "comment" });

第一个条件是应用的唯一条件,因为两个字段都是GregorianCalendar的实例。 有没有其他方法可以引用字段或其他方式我可以选择性地格式化它们,记住它们都是相同的类型?

1 个答案:

答案 0 :(得分:0)

我想说最干净的解决方案是创建两个Converter,然后将转换器应用于列,如下所示:

table.setConverter("myPropertyId", new MyConverter());

以下是Converter实施的示例:

public class MyConverter implements Converter<String, GregorianCalendar> {
    @Override
    public GregorianCalendar convertToModel(String value, Class<? extends GregorianCalendar> targetType, Locale locale) throws ConversionException {
        throw new ConversionException("Converting from Presentation to Model is not supported.");
    }

    @Override
    public String convertToPresentation(GregorianCalendar value, Class<? extends String> targetType, Locale locale) throws ConversionException {
        // TODO do the conversion here
        return null;
    }

    @Override
    public Class<GregorianCalendar> getModelType() {
        return GregorianCalendar.class;
    }

    @Override
    public Class<String> getPresentationType() {
        return String.class;
    }
}