我有一个类,其中包含 java.time.LocalDateTime 类型的属性。
public class MyClass{
// ...
private LocalDateTime fecha;
// ...
}
我正在使用 Spring 数据存储库。我想要完成的是根据日期查询实体:
@Service
public interface IRepository extends CrudRepository<MyClass, UUID> {
// ...
public void deleteByFecha(LocalDate fecha);
// ...
}
但这不起作用,因为会引发异常:
org.springframework.dao.InvalidDataAccessApiUsageException:参数值[2016-10-05]与预期类型[java.time.LocalDateTime(n/a)]不匹配;
所以问题是如何在数据库中查询 MyClassfecha但有 LocalDate?
EDIT为了防止有人遇到同样的问题,我想出了一个解决方案:修改存储库的方法,使其如下所示:
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);
// ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)