我有一个名为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());
}
答案 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>