How to query LocalDateTime with LocalDate?(如何使用 LocalDate 查询 LocalDateTime?)
问题描述
我有一个包含 java.time.LocalDateTime 类型属性的类.
I've got a class which contains an atttribute of java.time.LocalDateTime type.
public class MyClass{
// ...
private LocalDateTime fecha;
// ...
}
我正在使用 Spring Data 存储库.我想要完成的是根据日期查询实体:
I'm using Spring Data repositories. What I want to accomplish is to query entities according to a date:
@Service
public interface IRepository extends CrudRepository<MyClass, UUID> {
// ...
public void deleteByFecha(LocalDate fecha);
// ...
}
但这不起作用,因为抛出了异常:
But this does not work, as an exception is thrown:
org.springframework.dao.InvalidDataAccessApiUsageException: 参数值 [2016-10-05] 与预期类型不匹配 [java.time.LocalDateTime (n/a)];
org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [2016-10-05] did not match expected type [java.time.LocalDateTime (n/a)];
所以问题是如何通过 fecha 查询数据库中的 MyClass 但使用 LocalDate?
So the question is how can I query MyClass in database by fecha but with a LocalDate?
编辑万一有人遇到同样的问题,我想出了一个解决方案:修改存储库的方法,使其如下所示:
EDIT Just in case somebody faces the same issue, I've come up with one solution: modify the Repository's method so that it looks as follows:
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);
// ...
}
这篇关于如何使用 LocalDate 查询 LocalDateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 LocalDate 查询 LocalDateTime?


- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01