How to enter timestamp in Vaadin 8

血红的双手。 提交于 2020-02-25 03:03:11

问题


I am trying to enter timestamp using DateTimeField but in my entity i am having java.sql.timestamp. Converting datetimefield to timestamp is giving error

ConversionClass

package com.vaadin.convertor;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import com.vaadin.data.Converter;
import com.vaadin.data.Result;
import com.vaadin.data.ValueContext;
@SuppressWarnings("serial")
public class StringTimestampConvertor implements Converter<LocalDateTime, 
Timestamp> {

@SuppressWarnings("unchecked")

public Result<Timestamp> convertToModel(LocalDateTime value, ValueContext 
 context) {
    Result<Timestamp> rs =  (Result<Timestamp>) Timestamp.valueOf(value);
    return rs;
}

@Override
public LocalDateTime convertToPresentation(Timestamp value, ValueContext 
 context) {
    // TODO Auto-generated method stub
    return null;
    }
}

This is giving error that Timestamp cannot be casted into Result


回答1:


This is giving error that Timestamp cannot be casted into Result

This is not a correct way of casting (You cannot cast a Timestamp class to a Result)

Result<Timestamp> rs = (Result<Timestamp>) Timestamp.valueOf(value);

You should do instead Result.ok(Timestamp.valueOf(value)); ( Result interface)




回答2:


You have two possibilities:

  1. Evaluate to change the type of the date in your entity
  2. Manage the conversion of the dates

If you choose the second path, you have to know that the type managed by the Vaadin 8 DateTimeField is the Java 8 LocalDateTime. You can manage the conversion easily doing something like this:

LocalDateTime localDateTime = myField.getValue();
Timestamp timestamp = Timestamp.valueOf(localDateTime);

Then you will have the variable named timestamp as java.sql.Timestamp ready to be used in your entity.

UPDATE:

Since you are using a custom converter, you need to wrap the value into a Vaadin Converter Result. Casting your value into a Result is not a solution because they are objects of totally different types. You need instead to do something like this:

public Result<Timestamp> convertToModel(LocalDateTime value, ValueContext 
    context) {
    return Result.ok(Timestamp.valueOf(value));
}


来源:https://stackoverflow.com/questions/59573648/how-to-enter-timestamp-in-vaadin-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!