zoukankan      html  css  js  c++  java
  • JPA query between的多种方式(mongodb为例)

    背景

    JPA+MongoDB查询,给定一段时间范围查询分页结果,要求时间范围包含。

    Page<Log> findByCtimeBetweenOrderByCtime(
                LocalDateTime startTime, LocalDateTime endTime, Pageable pageable);
    

    这时候打印的日志为:

    find using query: { "ctime" : { "$gt" : { "$date" : 1605682694000 }, "$lt" : { "$date" : 1605682800000 } } 
    

    没有包含时间范围的边界,不符合要求

    实现一

    这个实现很骚,官网有解释:
    官网解释截图

    查询代码:

    @Query(value = "{'ctime': {$gte : ?0, $lte : ?1}}")
    Page<Log> findByCtimeBetweenOrderByCtime(
                LocalDateTime startTime, LocalDateTime endTime, Pageable pageable);
    

    这时候打印的日志为:

    find using query: { "ctime" : { "$gte" : { "$date" : 1605682694000 }, "$lte" : { "$date" : 1605682800000 } }
    

    可以看到,已经包含了时间范围。

    实现二

    Range<LocalDateTime> timeRange = Range.from(Range.Bound.inclusive(startTime)).to(Range.Bound.inclusive(endTime));
    Page<Log> page = logRepository.findByCtimeBetweenOrderByCtime(timeRange, pageable);
    ...
    Page<ScheduleLog> findByCtimeBetweenOrderByCtime(Range<LocalDateTime> timeRange, Pageable pageable);
    

    这里的LocalDateTime不支持,因为LocalDateTime实现的Comparable接口中给定的范型参数不是LocalDateTime,不符合参数要求,但是换个查询类型就可以了,比如Integer此类的。

    实现三

    @Query("select * from Log where ctime >= ?0 and ctime <= ?1")
    Page<Log> findByCtimeBetweenOrderByCtime(
                LocalDateTime startTime, LocalDateTime endTime, Pageable pageable);
    

    这种方案我个人不太喜欢,哈哈,就是想用对象,不想写过程查询语句。

    参考

  • 相关阅读:
    数据库特性之原子性和一致性
    [linux] 输出重定向与后台运行
    shell编程其实真的很简单(一)
    Java8中的流操作-基本使用&性能测试
    Hadoop到底是干什么用的?
    为什么要有文件系统?文件系统都有哪些种类?
    MySQL insert value与values
    MySQL create语句
    fiddler抓包-简单易操作(二)
    jmeter文件目录说明(一)
  • 原文地址:https://www.cnblogs.com/mrcharleshu/p/14037713.html
Copyright © 2011-2022 走看看