在LocalDateTime字段上使用DATE()函数进行MySQL查询

时间:2018-04-20 07:17:07

标签: mysql sql spring hibernate jpa

我有这样的查询:

@Query("SELECT rhwp.pk.reservation FROM ReservationHasWorkingPlace rhwp WHERE rhwp.pk.workingPlace.idWorkingPlace = ?1 AND NOT (DATE(rhwp.pk.reservation.endDateTime) < ?2 OR DATE(rhwp.pk.reservation.startDateTime) > ?3)")
List<Reservation> getReservationsForWPAndDateInterval(Integer idWorkingPlace, LocalDate startDate, LocalDate endDate);

我将存储在数据库中的DateTime与通过java方法传递的localDate进行比较。 我收到了这个例外:

Caused by: java.lang.IllegalArgumentException: Parameter value [2018-04-20] did not match expected type [java.util.Date (n/a)]

有一种方法可以配置hibernate / jpa自动进行转换,或者我必须传递Date对象而不是LocalDate? 我尝试导入甚至hibernate-java8但没有改变

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>${hibernate.version}</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-java8</artifactId>
    <version>${hibernate.version}</version>
</dependency>

2 个答案:

答案 0 :(得分:0)

您可以简单地使用@Converter。将LocalDateTime转换为时间戳的示例:

@Converter
public class SomeConverterName implements AttributeConverter<LocalDateTime, Timestamp> {

    @Override
    public Timestamp convertToDatabaseColumn(final LocalDateTime locDateTime) {
        return Timestamp.valueOf(locDateTime);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(final Timestamp sqlTimestamp) {
        return sqlTimestamp.toLocalDateTime();
    }
}

然后在实体字段中使用:

@Column(name = "somefield")
@Convert(converter = SomeConverterName.class)
private LocalDateTime someDate;

答案 1 :(得分:0)

使用java.sql.Date.valueOf(start)转换