JPA 查询以检查特定年月的记录是否存在?

cam*_*ode 3 java jpa spring-data-jpa spring-boot

我正在尝试实现一个 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
          }
     }
Run Code Online (Sandbox Code Playgroud)

Ram*_*Ali 6

您不需要获取所有记录。如果您只是尝试通过比较时间戳的 MONTH 和 YEAR 来过滤记录,请按照以下步骤操作

方法 1:

  • 构造 startDate(当年的第一天)
  • 构造 endDate(当年的最后一天)
  • 关键字之间使用并构造一个 jpa 查询,如下所示

方法 2:

  • 使用@Query注释构建 jpa 查询,如下所示

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

默认情况下,spring data 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);
Run Code Online (Sandbox Code Playgroud)