Reputation: 72
I am trying to format the datetime by using @Convert(converter = MyConverter.class)
.
This is working as expected while saving and data is properly saved in the DB.
The issue I am facing is the object that's being returned while responseEntity = myrepository.save(myEntity)
is not having the formated date. The field in the responseEntity is still returning old format. Am I missing anything?
My converter class:
public class DateTimeConverter implements
AttributeConverter<LocalDateTime, String> {
@Override
public String convertToDatabaseColumn(LocalDateTime attribute) {
if(Objects.isNull(attribute)) {
return null;
}
attribute = attribute.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return attribute.format(formatter);
}
@Override
public LocalDateTime convertToEntityAttribute(String dbData) {
if(Objects.isNull(dbData)) {
return null;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return LocalDateTime.parse(dbData, formatter);
}
}
Upvotes: 2
Views: 1840
Reputation: 115
Ran into a similar problem and discovered that the attribute conversion wasn't done by save()
but it was done by saveAndFlush()
. Breakpoints within the conversion weren't hit during save()
but were by saveAndFlush()
. If save()
was used the conversion was hit on a subsequent find...
query. This was also an issue if save
should have thrown an exception as it got delayed until flush
or subsequent query.
Upvotes: 1
Reputation: 18480
repository.save()
does return the converted value, entity value converted before flush time. It only attached to the persistence context.
But you want converted value using convertToEntityAttribute
. convertToEntityAttribute
only called when you fetch from the database.
Do this operation in service
entity.setProperty(entity.getProperty().atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime());
Upvotes: 0