我正在使用 JPA 2.3.1 和 JDBC 5.2.7,当我尝试使用 PostGreSQL DB 中的 JPA RepoLocalDateTime
作为参数类型查询表时。它不断收到此错误:
Parameter value [2020-12-08T07:35] did not match expected type [java.time.LocalDateTime (n/a)]
我还尝试使用转换为但也不起作用@Convert
的自定义类添加自定义属性。LocalDateTime
Timestamp
EventEntity.class 具有如下属性:
@Column(name = "event_timestamp",nullable = false)
@JsonSerialize(using = CustomLocalDateTimeSerializer.class)
@Convert(converter = LocalDateTimePersistenceConverter.class)
LocalDateTime eventTimestamp;
CustomLocalDateTimeSerializer
类只是将日期时间值序列化以
"yyyy-MM-dd HH:mm:ss.SSS"
用于DateTimeFormatter
以这种格式插入到列记录中。
LocalDateTimePersistenceConverter.class 转换如下:
@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;
}
}
用于搜索的类如下:
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class SearchCriteria {
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
LocalDateTime eventTimestamp;
}
这是查询方法:
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);
我根据研究实现了这个转换,这个版本的 JPA 还不能自动转换LocalDateTime
为它正在使用的java.util.timestamp
.