So I have this object saved to the database with one property being dateCreated
which is, of course, saved as MySQL timestamp. But while sending the data to the client, I want to be in milliseconds. Right now, I've mapped it to the Date
object and converting it to milliseconds further. But I thought, what if I could map my POJO in such a way that it retrieves values in milliseconds. Here is what I've tried.
OmsJob:
@Entity
@EntityListeners(PreventAnyUpdate.class)
@ConfigurationProperties("omsjob")
@Table(name = "OMSJob")
public class OmsJob {
@Id
@NotNull
@Column(name = "jobId")
private String id;
@NotNull
private Long dateCreated; // If I map this property to Date, it works fine
}
I thought I'll add a custom converter that'll convert java.util.Date
or java.sql.Date
to milliseconds. But it isn't working:
@Component
@ConfigurationPropertiesBinding
public class DateConverter implements Converter<Date, Long> {
@Override
public Long convert(Date date) {
return date.getTime();
}
}
The error I am getting is pretty obvious but is there any way to achieve what I am trying to?
ERROR 229770 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Unsupported conversion from TIMESTAMP to java.lang.Long
An attribute won't know about its converter until you declare it. Do it as follows:
@NotNull
@Convert (converter = DateConverter.class)
private Long dateCreated;
Also, change the converter as follows:
public class DateConverter implements AttributeConverter<Date, Long> {
@Override
public Date convertToDatabaseColumn(Long millis) {
retrun new Date(millis);
}
@Override
public Long convertToEntityAttribute(Date date) {
return date.getTime();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.