dateField in String

Hi,

I had column in database whose datatype is in varchar but it accepts value in dateformat.

On my browse screen i want to set the value for the field in dateformat dd/MMM/yyyy but since datatype is varchar it throws exception as “IllegalArgumentException: Unsupported date type class java.lang.String”. So is there any solution that user must select able to select date and the same value Stored in string in database.

expiryDate

expiry

Hi Adnan,

Create a JPA converter between LocalDate and String, for example:

package com.company.onboarding.entity;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Converter
public class DateToStringConverter implements AttributeConverter<LocalDate, String> {

    @Override
    public String convertToDatabaseColumn(LocalDate attribute) {
        return attribute != null ? attribute.format(DateTimeFormatter.ISO_DATE) : null;
    }

    @Override
    public LocalDate convertToEntityAttribute(String dbData) {
        return dbData != null ? LocalDate.parse(dbData, DateTimeFormatter.ISO_DATE) : null;
    }
}

The entity attribute should be of type LocalDate and the database column of type VARCHAR. Apply the converter on the attribute:

@Column(name = "DATE_", columnDefinition = "varchar(100)")
@Convert(converter = DateToStringConverter.class)
private LocalDate date;

public LocalDate getDate() {
    return date;
}

public void setDate(LocalDate date) {
    this.date = date;
}
2 Likes

Thank you for solution