JPA-QL query find all entities with LocalDateTime timestamp between LocalDate startDate and LocalDate endDate

4k Views Asked by At

I have a JPA entity TimeSlot with a LocalDateTime field called startDateTime:

@Entity
public class TimeSlot {

    private LocalDateTime startDateTime;
    ...
}

I am using Hibernate on WildFly 10.1. How do I query all entities with the startDateTime between startDate and endDate?

private List<TimeSlot> getTimeSlotsByStartDateEndDate(LocalDate startDate, LocalDate endDate) {
    return entityManager.createNamedQuery("TimeSlot.findByStartDateEndDate", TimeSlot.class)
            .setParameter("startDate", startDate)
            .setParameter("endDate", endDate).getResultList());
}

This query fails because a timestamp is not a date:

@NamedQueries({
        @NamedQuery(name = "TimeSlot.findByStartDateEndDate",
                query = "select t from TimeSlot t" +
                        // fails because a timestamp is not a date
                        " where t.startDateTime between :startDate and :endDate"),
})
1

There are 1 best solutions below

0
On

You must convert LocalDateTime and LocalDate to java.sql.Timestamp then add your converter classes to the persistent.xml file then everything must be ok. For LocalDateTimeConverter :

import java.time.LocalDateTime;
import java.sql.Timestamp;
 
@Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
     
    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime locDateTime) {
        return locDateTime == null ? null : Timestamp.valueOf(locDateTime);
    }
 
    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
        return sqlTimestamp == null ? null : sqlTimestamp.toLocalDateTime();
    }
}

For LocalDateTime:

import java.sql.Date;
import java.time.LocalDate;
 
@Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> {
     
    @Override
    public Date convertToDatabaseColumn(LocalDate locDate) {
        return locDate == null ? null : Date.valueOf(locDate);
    }
 
    @Override
    public LocalDate convertToEntityAttribute(Date sqlDate) {
        return sqlDate == null ? null : sqlDate.toLocalDate();
    }
}

Lastly, add your classes to the persistent.xml

<class>xxxx.model.Entities</class>
<class>xxxx.converter.LocalDateConverter</class>
<class>xxxx.converter.LocalDateTimeConverter</class>