1

我有一个 JPA 实体 TimeSlot,其LocalDateTime字段名为startDateTime

@Entity
public class TimeSlot {

    private LocalDateTime startDateTime;
    ...
}

我在 WildFly 10.1 上使用休眠。如何使用startDateTimebetweenstartDate和查询所有实体endDate

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

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

@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"),
})
4

1 回答 1

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

对于本地日期时间:

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>
于 2020-10-03T17:50:38.900 回答