I have an JPA entity with an attribute of type java.time.LocalDateTime
. I use a javax.persistence.Converter
annotation for this to work. I can load the entity and save it without problems, but when I try to execute a jpql query like this:
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));
I get an error like this:
Caused by: org.postgresql.util.PSQLException: ERROR: operator does not exist: bytea >= timestamp without time zone
I've tried many things but couldn't get the parameter to work. I even tried to use java.util.Date
and java.util.Calendar
as the parameter but it also doesn't work.
Why does JPA not support LocalDate and LocalDateTime? The answer is simple, JPA 2.1 was released before Java 8 and the Date and Time API simply didn't exist at that point in time. Therefore the @Temporal annotation can only be applied to attributes of type java.
Set; @Entity public class MyObject { @Id private String id; private LocalDate startdate; private LocalDate enddate; public MyObject() {} public MyObject(LocalDate enddate) { this. startdate = LocalDate. now(); this. enddate = enddate; } ... }
LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision.
I've seen in the comment that you want to query Timestamp
q.setParameter("currentDateTime", new Date(), TemporalType.TIMESTAMP)
So your converter must be LocalDateTime
⇔Timestamp
I've done this with Hibernate as a JPA provider, and my code looks like this in my 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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With