【问题标题】:DateField Vaadin Component with SQL Date带有 SQL 日期的 DateField Vaadin 组件
【发布时间】:2017-11-12 16:39:29
【问题描述】:

所以,我的 POJO 类中有一个属性 SQL.Date。我想使用 Vaadin 组件中的 Binder 来绑定它,但总是这样返回:

Property type 'java.sql.Date' doesn't match the field type 'java.time.LocalDate'. Binding should be configured manually using converter.

所以这是我在 POJO 类中包含的 Getter Setter

public Date getDateOfBirth() {
    return dateOfBirth;
}

public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; }

这是我使用 Binder 组件的时候:

binder = new Binder<>(Person.class);
binder.bindInstanceFields( this );

仅供参考,我使用 Spring Boot JPA 获取数据。报错信息和Spring Boot的使用有关系吗?

【问题讨论】:

  • 哪个版本? Vaadin8?
  • 是的,Vaadin 8.0.0
  • 如果您不提供完整的堆栈跟踪,则很难判断是哪个库导致它。

标签: java spring-boot spring-data-jpa vaadin sql-date-functions


【解决方案1】:

这个

属性类型“java.sql.Date”与字段类型不匹配 'java.time.LocalDate'。绑定应该使用手动配置 转换器。

告诉我们该做什么。在没有看到您的代码的情况下,我假设您在尝试使用 java.sql.Date 值(或 binder.bindInstanceFields() 尝试)填充的某个 Vaadin FormLayout 中有 Vaadin DateField

不幸的是DateField 似乎只接受LocalDate。因此,您需要以某种方式转换该值。

在 vaadin Converter 类型层次结构中有很多不同的“日期”转换器,但缺少这个(或者我可能错过了?)所以我创建了它:

public class SqlDateToLocalDateConverter
       implements Converter<LocalDate,java.sql.Date> {
    @Override
    public Result<java.sql.Date> convertToModel(LocalDate value,
           ValueContext context) {
        if (value == null) {
            return Result.ok(null);
        }
        return Result.ok( java.sql.Date.valueOf( value) );
    }
    @Override
    public LocalDate convertToPresentation(java.sql.Date value,
           ValueContext context) {
        return value.toLocalDate();
    }
}

您似乎使用的是声明式 ui?我现在无法告诉它如何毫不费力地移植它。

如果您手动绑定字段,它会是这样的:

    binder.forField(myForm.getMyDateField())
       .withConverter(new SqlDateToLocalDateConverter())
       .bind(MyBean::getSqlDate, MyBean::setSqlDate);

所以我想你需要找到一种方法来添加这个转换器来处理假定的DateField。无论如何,消息表明您可能无法使用简单的方法binder.bindInstanceFields(),而是手动绑定字段。

【讨论】:

  • 啊,好吧。感谢您的解释,也感谢转换器的源代码。真的很感激
【解决方案2】:

您可以创建自定义日期字段并使用它来代替 DateField。那你就不用每次都绑定了,用自动绑定就行了

public class CustomDateField extends CustomField<Date> {
    DateField dateField;

    public CustomDateField(String caption) {
        setCaption(caption);
        dateField = new DateField();
        dateField.setDateFormat("dd/MM/yy");
    }

    @Override
    protected Component initContent() {
        return dateField;
    }

    @Override
    protected void doSetValue(Date date) {
        dateField.setValue(date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
    }

    @Override
    public Date getValue() {
        return dateField.getValue() != null ? Date.from(dateField.getValue().atStartOfDay(ZoneId.systemDefault()).toInstant()) : null;
    }
}

【讨论】:

  • 哇。我刚刚意识到我们可以在 Vaadin 中创建一个自定义类。谢谢你的回答。
猜你喜欢
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-17
  • 1970-01-01
  • 2014-06-24
  • 2014-09-04
相关资源
最近更新 更多