JPA-QL查询在LocalDate startDate和LocalDate endDate之间查找具有LocalDateTime时间戳的所有实体

时间:2017-05-31 18:36:53

标签: java hibernate jpa jsr310

我有一个名为LocalDateTime的{​​{1}}字段的JPA实体TimeSlot:

startDateTime

我在WildFly 10.1上使用Hibernate。如何在@Entity public class TimeSlot { private LocalDateTime startDateTime; ... } startDateTime之间使用startDate查询所有实体?

endDate

此查询失败,因为时间戳不是日期:

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

1 个答案:

答案 0 :(得分:0)

您必须将LocalDateTime和LocalDate转换为java.sql.Timestamp,然后将转换器类添加到persistent.xml文件中,然后一切正常。 对于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();
    }
}

对于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();
    }
}

最后,将您的类添加到persistent.xml

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