java.sql.timestamp的vaadin转换器[英] Vaadin converter for java.sql.Timestamp

本文是小编为大家收集整理的关于java.sql.timestamp的vaadin转换器的处理方法,想解了java.sql.timestamp的vaadin转换器的问题怎么解决?java.sql.timestamp的vaadin转换器问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

我正在使用PostgreSQL数据库,时间戳列具有Java.sql.timestamp类.即使此类扩展了java.util.date,当我编辑popupdatefiels时,我也会获得错误

无法将Java.util.date类型的值转换为模型类型Java.sql.timestamp.没有设置转换器,并且类型不兼容.

默认转换器工厂无法正常工作.我试图写

dateField.setConverter(new DateToSqlDateConverter());

dateField.setConverter(StringToDateConverter.class);

与相同的结果.
通过单击日历中的一天,我可以以欧洲格式看到有效的日期和时间" 23.10.2014 13.44",但是在控制台上使用类似消息的提交失败:

Caused by: com.vaadin.data.util.converter.Converter$ConversionException: Could not convert value to Timestamp
at com.vaadin.ui.AbstractField.convertToModel(AbstractField.java:725)
at com.vaadin.ui.AbstractField.getConvertedValue(AbstractField.java:811)
at com.vaadin.ui.AbstractField.commit(AbstractField.java:247)
... 42 more
Caused by: com.vaadin.data.util.converter.Converter$ConversionException: Unable to convert value of type java.util.Date to model type class java.sql.Timestamp. No converter is set and the types are not compatible.
at com.vaadin.data.util.converter.ConverterUtil.convertToModel(ConverterUtil.java:181)
at com.vaadin.ui.AbstractField.convertToModel(AbstractField.java:745)
... 45 more

在哪里可以获得适当的转换器?感谢您的建议.

推荐答案

我推荐这种方式:

PopupDateField pdf = new PopupDateField();
Timestamp ts = new Timestamp(System.currentTimeMillis());
ObjectProperty<Timestamp> prop = new ObjectProperty<Timestamp>(ts);
pdf.setPropertyDataSource(prop);
pdf.setConverter(MyConverter.INSTANCE);

使用此转换器:

public class MyConverter implements Converter<Date, Timestamp> {

    private static final long serialVersionUID = 1L;
    public static final MyConverter INSTANCE = new MyConverter();

    @Override
    public Timestamp convertToModel(Date value,
            Class<? extends Timestamp> targetType, Locale locale)
            throws ConversionException {
        return value == null ? null : new Timestamp(value.getTime());
    }

    @Override
    public Date convertToPresentation(Timestamp value,
            Class<? extends Date> targetType, Locale locale)
            throws ConversionException {
        return new Date(value.getTime());
    }

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

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

    private Object readResolve() {
        return INSTANCE; // preserves singleton property
    }

}

其他推荐答案

不要将java.sql.Timestamp视为java.util.Date

的子类

while java.sql.Timestamp java.sql.Timestamp 从技术上讲,从 java.util.Date ,班级文档的最后一段指出,您不应该考虑这样做,您应该忽略这一事实.

由于上述时间戳类别和java.util.date类之间的差异,建议代码不要将时间戳值视为java.util.date的实例.时间戳和java.util.date之间的继承关系确实表示实现的继承,而不是键入继承.

换句话说,此类结构是笨拙的骇客.早期Java的日期时间课程被匆忙进行,并且经过深思熟虑.

转换的一个问题是java.sql.timestamp具有纳秒分辨率,但是java.util.date只有毫秒,因此数据将丢失.

提防Vaadin用SQLContainer备份网格(大概是一个表)犯了这个错误. SQLContainer中的Java.sql.timestamp柱被视为Java.util.date(SuperClass),因此如果涉及微秒或纳秒,则丢失了数据. (请参阅下面的转换器实现.)

java.Time

新的/a>在Java 8及以后是这些旧课程的重新思考,从头开始.这些新课程的灵感来自 joda time ,由 jsr 310 ,并由 threeten-extra project .

java.Time类是为纳秒分辨率构建的.因此,在Java.Time.intant和Java.sql.timestamp之间转换时没有数据丢失.

旧的和新的日期时间类都有在新旧之间来回转换的方法.注意以下调用的java.sql.Timestamp::toInstant和Timestamp.from( instant )方法.

Java.Time.instant ststant的转换器

此示例可能会或可能无助于回答这个问题.我正在转换java.sql.timestamp数据以显示为java.time.instant的字符串.

除了文本格式外,请记住我的转换器和默认器之间还有一个 big :没有数据丢失! (请参见上面的讨论)此示例屏幕截图发生没有任何分数秒.但是,如果它确实具有微秒或纳秒秒,则该数据将被保留并按照需要显示.

两个网格的两列的屏幕截图,其中一列使用此处呈现的转换器,用于即时到java.sql.timestamp,另一台使用默认转换器用于date

这是一些代码,执行 Instant 从java.sql.timestamp转换.换句话说:

  • 演示文稿:字符串(使用 iso_instant 格式化)
  • 模型: java.sql.timestamp

此代码从源代码 com.vaadin.data.util.converter.StringToDateConverter 与vaadin 7.

捆绑在一起的类

此代码在显示 SQLContainer vaadin 7.5.2中的对象的java.sql.timestamp列中的 Grid .我还没有尝试过 Table .

在为我工作时,此代码可能需要清理.特别是(a)评论可能是错误的,(b)我打电话给 slf4j 记录您可能需要更改/删除.

默认 iso 8601 格式很难为人类阅读,所以我是人类为更改格式和调整时区的替代方案.

要使用此类,您必须在上拨打setConverter Grid.Column 对象.或配置 ConverterFactory ConverterFactory a href =" https://vaadin.com/wiki/-/wiki/main/main/changing%20the%20default%20Converters%20For%20ANP%20Application" rel =" nofollow noreferrer">此Wiki Page ./p>

package com.powerwrangler.util;

import com.vaadin.data.util.converter.Converter;
import java.text.DateFormat;
import java.time.format.DateTimeParseException;
import java.sql.Timestamp;
import java.util.Locale;
import java.time.Instant;
import org.slf4j.LoggerFactory;

/**
 *
 * Converts java.sql.Date objects for presentation as String in format of a java.time.Instant object.
 *
 * String format by default is DateTimeFormatter.ISO_INSTANT, such as '2011-12-03T10:15:30Z'.
 *
 * Based on code from Vaadin’s bundled StringToDateConverter.java
 *
 * PRESENTATION: String (of an Instant)
 *
 * MODEL: java.sql.Date
 *
 * @author Basil Bourque.
 * 
 * This code is derived from the com.vaadin.data.util.converter.StringToDateConverter class bundled with Vaadin 7. 
 * That original class was published with this Copyright:
 * 
 * Copyright 2000-2014 Vaadin Ltd.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 * 
 */
public class StringOfInstantToSqlTimestampConverter implements Converter<String , Timestamp>
{

    // Member vars.
    final org.slf4j.Logger logger = LoggerFactory.getLogger( this.getClass() );

    /**
     * Returns the format used by {@link #convertToPresentation(Date, Class,Locale)} and
     * {@link #convertToModel(String, Class, Locale)}.
     *
     * @param locale The locale to use
     *
     * @return A DateFormat instance
     */
    protected DateFormat getFormat ( Locale locale ) {
        if ( locale == null ) {
            locale = Locale.getDefault();
        }

        DateFormat f = DateFormat.getDateTimeInstance( DateFormat.MEDIUM , DateFormat.MEDIUM , locale );
        f.setLenient( false );
        return f;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.vaadin.data.util.converter.Converter#convertToModel(java.lang.Object, java.lang.Class, java.util.Locale)
     */
    @Override
    public Timestamp convertToModel ( String value , Class<? extends Timestamp> targetType , Locale locale )
            throws com.vaadin.data.util.converter.Converter.ConversionException {
        if ( targetType != getModelType() ) {
            throw new Converter.ConversionException( "Converter only supports "
                    + getModelType().getName() + " (targetType was "
                    + targetType.getName() + ")" );
        }

        if ( value == null ) {
            return null;
        }

        // Remove leading and trailing white space
        String trimmed = value.trim();

//        ParsePosition parsePosition = new ParsePosition( 0 );
//        Date parsedValue = this.getFormat( locale ).parse( trimmed , parsePosition );
//        if ( parsePosition.getIndex() != trimmed.length() ) {
//            throw new Converter.ConversionException( "Could not convert '" + trimmed + "' to " + getModelType().getName() );
//        }
        Instant instant = null;
        try {
            instant = Instant.parse( trimmed ); // Uses DateTimeFormatter.ISO_INSTANT.
        } catch ( DateTimeParseException e ) {
            throw new Converter.ConversionException( "Could not convert '" + trimmed + "' to java.time.Instant on the way to get " + getModelType().getName() );
        }
        if ( instant == null ) {
            logger.error( "The instant is null after parsing. Should not be possible. Message # ACE6DA4E-44C8-434C-A2AD-F946E5CFAEFD." );
            throw new Converter.ConversionException( "The Instant is null after parsing while attempting to convert '" + trimmed + "' to java.time.Instant on the way to get " + getModelType().getName() + "Message # 77A767AB-7D42-490F-9C2F-2775F4443A8D." );
        }
        Timestamp parsedValue = Timestamp.from( instant );

        return parsedValue;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.vaadin.data.util.converter.Converter#convertToPresentation(java.lang .Object, java.lang.Class,
     * java.util.Locale)
     */
    @Override
    public String convertToPresentation ( Timestamp value , Class<? extends String> targetType , Locale locale )
            throws com.vaadin.data.util.converter.Converter.ConversionException {
        if ( value == null ) {
            return null;
        }

        Instant instant = value.toInstant();
        String dateTimeStringInIsoFormat = instant.toString();   // Uses DateTimeFormatter.ISO_INSTANT.
        return dateTimeStringInIsoFormat;
        //return getFormat( locale ).format( value );
    }

    /*
     * (non-Javadoc)
     *
     * @see com.vaadin.data.util.converter.Converter#getModelType()
     */
    @Override
    public Class<Timestamp> getModelType () {
        return Timestamp.class;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.vaadin.data.util.converter.Converter#getPresentationType()
     */
    @Override
    public Class<String> getPresentationType () {
        return String.class;
    }

}

本文地址:https://www.itbaoku.cn/post/1764123.html