I'm using JPA 2.3.1 and JDBC 5.2.7, When I try to query on table using JPA Repo in PostGreSQL DB using LocalDateTime as parameter type. It keeps getting this error:
Parameter value [2020-12-08T07:35] did not match expected type [java.time.LocalDateTime (n/a)]
I also tried to add Custom Attribute @Convert with custom class that converts LocalDateTime to Timestamp but also not working.
EventEntity.class having attribute as follows:
@Column(name = "event_timestamp",nullable = false)
@JsonSerialize(using = CustomLocalDateTimeSerializer.class)
@Convert(converter = LocalDateTimePersistenceConverter.class)
LocalDateTime eventTimestamp;
CustomLocalDateTimeSerializer class just serializes datetime value to
"yyyy-MM-dd HH:mm:ss.SSS" using DateTimeFormatter to be inserted into column record with this format.
LocalDateTimePersistenceConverter.class that converts as follows:
@Converter(autoApply = true)
public class LocalDateTimePersistenceConverter implements AttributeConverter<LocalDateTime, java.sql.Timestamp> {
@Override
public java.sql.Timestamp convertToDatabaseColumn(LocalDateTime entityValue) {
if (entityValue != null) {
return java.sql.Timestamp.valueOf(entityValue);
}
return null;
}
}
The class used to search with as follows:
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class SearchCriteria {
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
LocalDateTime eventTimestamp;
}
This is query method:
public void search(SearchCriteria sc){
Specification<EventEntity>
searchCriteria.add(new SearchCriteria("eventTimestamp",
SearchOperation.GreaterThanOrEqual , sc.getEventTimestamp()));
return new SpecificationsBuilder<EventEntity>(searchCriteria).build();
}
SearchCriteria sc = new SearchCriteria();
sc.setEventTimestamp(LocalDateTime.now());
Specification<EventEntity> searchSpecification =
search(sc);
List<EventEntity> entities = repository.findAll(searchSpecification);
I implemented this conversion according to research that this version of JPA cannot yet convert automatically to LocalDateTime as it is using java.util.timestamp.