使用MybtiesPlus的lambda表达式

// Timestamp 是java.sql包下的类
public static Timestamp getTimeStampByDate(Date date) {
    return new Timestamp(date.getTime());
  }
// happenedTime实体类的类型LocalDateTime
// happenedTime数据库表中字段类型为timestamp类型,mybatiesplus根据表自动生成的实体类为LocalDateTime类型
carAlarmInfoMapper.selectList(
            new QueryWrapper<CarAlarmInfo>().lambda()
                .ge(CarAlarmInfo::getHappenedTime,
     DateTool.getTimeStampByDate(carAlarmInfoBo.getStartTime()))
                .le(CarAlarmInfo::getHappenedTime,
     DateTool.getTimeStampByDate(carAlarmInfoBo.getEndTime())));
     

使用JPA动态拼接

JPA动态查询,拼接Specification
 private Specification<VehiclePassEntity> createSpecification(
      QueryParams queryParams) {
    return (root, criteriaQuery, criteriaBuilder) -> {
      List<Predicate> predicateList = new ArrayList<>();
        // 开始时间,参数为date类型
      if (!JudgeEmpty.isEmpty(queryParams.getStartTime())) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = null;
        Date endDate = null;
        try {
          startDate = format.parse(queryParams.getStartTime());
          endDate = format.parse(queryParams.getEndTime());
        } catch (Exception e) {
          logger.error("时间格式化失败");
        }
        predicateList.add(criteriaBuilder.between(root.<Date>get("passTime"), startDate, endDate));
      }
      return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
    };
  }


根据时间查数据sql

方法一:直接比较

select * from 表名 where 时间字段>= '2022-01-01 00:00:00' and 时间字段< '2022-01-15 00:00:00';

方法二:sql中between and

select * from 表名 where 时间字段 between '2022-01-01 00:00:00' and '2022-01-15 00:00:00';

方法三:TO_DATE或TO_TIMESTAMP方法

// SQL中不区分大小写,MM和mm被认为是相同的格式代码,所以采用了mi代替分钟,24代表24小时时间制
select * from 表名 where 时间字段 between to_date('202-01-01','YYYY-MM-DD') and to_date('2022-01-15','YYYY-MM-DD');
// 在pgsql中to_date方法用如下方式,按天筛选
1to_date(createddate::text,'YYYY-MM-DD')
2to_date(cast(createddate as TEXT),'YYYY-MM-DD')
// 或者to_timestamp方法准确时间
1TO_TIMESTAMP('202-01-01 00:00:00'::text,'YYYY-MM-DD hh24:mi:ss')
2TO_TIMESTAMP(cast('2022-01-15 00:00:00' as TEXT),'YYYY-MM-DD hh24:mi:ss')

select * from 表名 where 时间字段 >= '2022-01-01 00:00:00'::timestamp and 时间字段< '2022-01-15 00:00:00'::timestamp;

to_date和to_timestamp方法

to_timestamp('2020-02-27 12:12:12','yyyy-MM-dd hh24:mi:ss') 
to_date('2020-02-27 12:12:12','yyyy-MM-dd hh24:mi:ss') 

结果:
to_timestamp返回结果:2020-02-27 12:12:12
to_date返回结果:2020-02-27
方法四:通过函数比较时间字段的某个值

select *  where  date_part('minute', now() - 数据库时间字段) > 30
           or date_part('day',now()-数据库时间字段)>0
           or date_part('hour',now()-数据库时间字段)>0
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐