I have a table with a varchar column which represent a data in yyyy-mm-dd format. However, this field could be an empty string.
| id | serial |
| date | varchar(10) |
I have my entity defined as
import jakarta.persistence.*;
@Entity
class Table {
@Id
private long Id;
private LocalDate date;
}
And I use a JpaRepository
findById()
The problem arise when column date's value is an empty string "" It's trying to convert binary empty string to a date from org.postgresql.jdbc.TimestampUtils. I am getting an IndexOutOfBoundException because it's not expecting the string to be empty.
I have a few solutions but they don't seem clean enough.
date
in my entity from LocalDate
to String
and do a manual conversion to LocalDate to a DTO. During this conversion, I have more freedom to convert empty string or null object if needed. I am not crazy about this solution since it adds extra step.So I am wondering if Jakarta entity has built in annotation where I could consider empty string as null? Or is there any other elegant way to circumvent this problem?
You can use AttributeConverter to convert empty string to null.
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import java.time.LocalDate;
@Converter
public class LocalDateConverter implements AttributeConverter<LocalDate, String> {
@Override
public String convertToDatabaseColumn(LocalDate date) {
if (date == null) {
return null;
}
return date.toString();
}
@Override
public LocalDate convertToEntityAttribute(String str) {
if (str == null || str.isEmpty()) {
return null;
}
return LocalDate.parse(str);
}
}
then use @Convert
@Convert(converter = LocalDateConverter.class)
private LocalDate date;