如何使用 LocalDate 查询 LocalDateTime?

rus*_*off 5 java spring spring-data java-time spring-repositories

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

public class MyClass{
    // ...
    private LocalDateTime fecha;
    // ...
}
Run Code Online (Sandbox Code Playgroud)

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

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

但这不起作用,因为抛出异常:

org.springframework.dao.InvalidDataAccessApiUsageException: 参数值 [2016-10-05] 与预期类型 [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);

}
Run Code Online (Sandbox Code Playgroud)

Cep*_*pr0 9

试试这个(未测试):

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);
    // ...
}
Run Code Online (Sandbox Code Playgroud)