问题
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:
- Evaluate to change the type of the date in your entity
- 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