Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

attribute of type java.time.LocalDateTime doesn't work as a JPA query parameter in Hibernate

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.

like image 589
Marcos Avatar asked May 19 '15 12:05

Marcos


People also ask

Does JPA support LocalDateTime?

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.

How do you persist LocalDate and LocalDateTime with JPA?

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; } ... }

What is Java LocalDateTime?

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.


1 Answers

I've seen in the comment that you want to query Timestamp

q.setParameter("currentDateTime", new Date(), TemporalType.TIMESTAMP)

So your converter must be LocalDateTimeTimestamp

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();
    }
}
like image 58
Xavier Gourmandin Avatar answered Sep 30 '22 00:09

Xavier Gourmandin