我有一个 JPA 实体,其属性类型为 java.time.LocalDateTime
。我使用 javax.persistence.Converter
注释来实现这一点。我可以加载实体并毫无问题地保存它,但是当我尝试执行这样的 jpql 查询时:
TypedQuery<Event> q = em.createQuery(
"SELECT e " +
"FROM Event e " +
"WHERE :currentDateTime >= e.startDateTime", Event.class);
q.setParameter("currentDateTime", LocalDateTime.now().withSecond(0).withNano(0));
我收到这样的错误:
Caused by: org.postgresql.util.PSQLException: ERROR: operator does not exist: bytea >= timestamp without time zone
我已经尝试了很多东西,但无法使参数起作用。我什至尝试使用 java.util.Date
和 java.util.Calendar
作为参数,但它也不起作用。
最佳答案
看到评论说要查询Timestamp
q.setParameter("currentDateTime", new Date(), TemporalType.TIMESTAMP)
所以你的转换器必须是LocalDateTime
⇔ Timestamp
我已经使用 Hibernate 作为 JPA 提供程序完成了此操作,我的代码在 AttributeConverter<LocalDateTime, Timestamp>
中看起来像这样
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime date) {
if (date == null) {
return null;
} else {
return Timestamp.valueOf(date);
}
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp value) {
if (value == null) {
return null;
} else {
return value.toLocalDateTime();
}
}
关于java - java.time.LocalDateTime 类型的属性在 Hibernate 中不能用作 JPA 查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30326004/