mysql查询localdatetime字段上的date()函数

q5lcpyga  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(635)

我有这样一个问题:

@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>
0lvr5msh

0lvr5msh1#

使用java.sql.date.valueof(start)进行转换是可行的

ngynwnxp

ngynwnxp2#

您可以简单地使用@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;

相关问题