我有一个jpa entity timeslot,带有LocalDateTime
字段,称为 startDateTime
:
@Entity
public class TimeSlot {
private LocalDateTime startDateTime;
...
}
我在野生蝇10.1上使用Hibernate。如何在startDate
和endDate
之间使用startDateTime
查询所有实体?
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"),
})
您必须将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();
}
}
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();
}
}
最后,将您的类添加到persistent.xml
<class>xxxx.model.Entities</class>
<class>xxxx.converter.LocalDateConverter</class>
<class>xxxx.converter.LocalDateTimeConverter</class>