【问题标题】:Spring Data JPA between date range return null日期范围之间的 Spring Data JPA 返回 null
【发布时间】:2021-07-01 02:32:51
【问题描述】:

我正在使用原生查询来查询运算符之间的日期,但它返回 null。 当我用静态日期运行它时

@Query(value ="SELECT  a.name,m.title  from meetings m ,attendies a where m.id =a.m_aid and (start_time BETWEEN '2021-04-03 11:00:16' AND '2021-04-03 11:30:15' )",nativeQuery = true)
public List<Object[]> findConflictMettinds( Date startTime, Date endTime );

能够获取数据,但是当尝试使用动态值返回时,它总是返回 null。 以下是我目前尝试过的不同方法

@Query(value ="SELECT  a.name,m.title  from meetings m ,attendies a where m.id =a.m_aid and (m.start_time BETWEEN ?1 AND ?2 )",nativeQuery = true)
public List<Object[]> findConflictMettinds(@Param("startTime") Date startTime,@Param("endTime") Date endTime );                                          @Query(value ="SELECT  a.name,m.title  from meetings m ,attendies a where m.id =a.m_aid and (m.start_time BETWEEN :startTime AND :endTime )",nativeQuery = true)
public List<Object[]> findConflictMettinds(@Param("startTime") Date startTime,@Param("endTime") Date endTime );

【问题讨论】:

  • 能否将日期参数作为字符串传递并使用 dateformatter 格式化日期 YYYY-MM-dd HH:mm:ss?
  • @Gurkanİlleez 是的,我用过 -> @JsonFormat(shape=JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss",timezone = "Asia/Kolkata")
  • 然后传递字符串参数来查询,而不是日期变量

标签: spring spring-boot hibernate spring-mvc spring-data-jpa


【解决方案1】:
@Query(value ="SELECT  a.name,m.title  from meetings m ,attendies a where m.id =a.m_aid and (m.start_time > :startTime AND m.start_time <:endTime )",nativeQuery = true)
public List<Object[]> findConflictMettinds(@Param("startTime") String startTime,@Param("endTime") String endTime );

SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

repository.findConflictMettinds(dateFormatter.format(startTime), dateFormatter.format(endTime))

您也不必使用本机查询,但如果有必要,您可以使用给定的示例。也可以找Search records between two dates using Spring Data JPA native query?

【讨论】:

  • @GurkanIllez 尝试使用字符串,但没有适合我
【解决方案2】:

尝试将日期字符串作为模型属性而不是参数传递

public List<Object[]> findConflictMettinds(@ModelAttribute("startTime") String startTime,@ModelAttribute("endTime") String endTime );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2022-10-13
    • 2014-11-28
    相关资源
    最近更新 更多