我正在尝试实现JPA查询,以检查是否存在日期时间戳与当前年月匹配的任何记录。现在,我正在获取所有记录并进行迭代以匹配。我知道这是不正确的实现,只是想知道是否有针对此场景的内置JPA查询。
这是我到目前为止的实现方式
List<Product> productList= productRepository.findAll();
/*getMonthInt() and getYearInt() is the custom function which returns current
month and year. As date.getMonth() and date.getYear() is deprecated
*/
int currentMonth=getMonthInt(new Date());
int currentYear=getYearInt(new Date());
for(Product product:productList){
int fetchedMonth=getMonthInt(product.getShipmentDate()) ;
int fetchedYear=getYearInt(product.getShipmentDate());
if(fetchedMonth == currentMonth && fetchedYear == currentYear){
//record exist
}
else{
//do something else
}
}
答案 0 :(得分:4)
您不需要获取所有记录。如果您只是通过比较时间戳的MONTH和YEAR来尝试过滤记录,请按照以下步骤操作
APPROACH-1:
APPROACH-2:
您的ProductRepository应该如下所示
public interface ProductRepository extends JpaRepository<Product, Integer> {
List<Product> findAllByShipmentDateBetween(Date startDate, Date endDate);
@Query("select p from Product p where year(p.shipmentDate) = ?1 and month(p.shipmentDate) = ?2")
List<Product> findAllByShipmentDate(Integer year, Integer month);
}
默认情况下,spring数据jpa使用基于位置的参数绑定,如第二种查询方法所示,这可能在维护期间引起问题。可以使用命名参数编写更可维护的代码。例如
@Query("select p from Product p where year(p.shipmentDate) = :year and month(p.shipmentDate) = :month")
List<Product> findAllByShipmentDate(@Param("year") Integer year, @Param("month") Integer month);