java - 如何用LocalDate查询LocalDateTime?

标签 java spring spring-data java-time spring-repositories

我有一个类,其中包含 java.time.LocalDateTime 类型的属性。

public class MyClass{
    // ...
    private LocalDateTime fecha;
    // ...
}

我正在使用 Spring Data 存储库。我想要完成的是根据日期查询实体:

@Service
public interface IRepository extends CrudRepository<MyClass, UUID> {
    // ...
    public void deleteByFecha(LocalDate fecha);
    // ...
}

但这不起作用,因为会引发异常:

org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [2016-10-05] did not match expected type [java.time.LocalDateTime (n/a)];

所以问题是如何通过 fecha 但使用 LocalDate 查询数据库中的 MyClass?

编辑 为了防止有人遇到同样的问题,我想出了一个解决方案:修改存储库的方法,使其如下所示:

import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
// ...

@Service
public interface IRepository extends CrudRepository<MyClass, UUID> {

    @Transactional
    @Modifying
    @Query("DELETE FROM MyClass mtc WHERE YEAR(mtc.fecha)=?1 AND MONTH(mtc.fecha)=?2 AND DAY(mtc.fecha)=?3")
    public void deleteByFecha(Integer year, Integer month, Integer day);

}

最佳答案

试试这个(未测试):

public interface IRepository extends CrudRepository<MyClass, UUID> {
    // ...
    default void delByFecha(LocalDate fecha) {

        deleteByFechaBetween(fecha.atStartOfDay(), fecha.plusDays(1).atStartOfDay());

    }

    void deleteByFechaBetween(LocalDateTime from, LocalDateTime to);
    // ...
}

关于java - 如何用LocalDate查询LocalDateTime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43977749/

相关文章:

java - Spring @RequestMapping 对特殊字符的处理

Spring Data Rest 发布到收集端点

spring-mvc - 启动tomcat时出错

java - 如何在启动时验证 Spring Data JPA 查询?

java - 使用 Drools 的声明式模型生成的类作为主要业务对象模型

java - 为什么在 JUnit 中不推荐使用 assertEquals(double,double)?

java - 强制 spring boot jackson 解串器使用 BigDecimal

java - 我如何在内存中加载数据库

java - 如何在 lambda 函数中延迟初始化 Map?

java - 设置 HTTP 响应代码和 HTTP 方法