javapostgresqlspring-data-jpa

Postgres empty varchar as null instead of empty string in Spring Data JPA


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.

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?


Solution

  • 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;