java 8 lambda表达式和mybatis-plus中结合使用,根据今日时间返回倒序最新数据 queryWrapper常用方法及简单应用


mybatis-plus中查询对象 queryWrapper常见方法

众所周知
mybatis-plus支持 Lambda 形式调用:及通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错。
那么到底在项目中我们该如何使用呢,就让我们来看看吧
大家可以插个眼方便日后查看哦!
QueryWrapper与lambda表达式结合查询,这里直接使用lambdaQueryWrapper也是可以的!

List<ProjectSms> list = list(new QueryWrapper<ProjectSms>().()
        .eq(ProjectSms::getPhoneNumbers,phoneNumbers)    获取ProjectSms中字段phoneNumbers相等的
        .gt(ProjectSms::getSendTime,LocalDateTime.of(LocalDate.now(), LocalTime.MIN))  拿到sendtime中大于今天00:00的数据(即今日的数据)
        .orderByDesc(ProjectSms::getSendTime));根据sengtime倒序输出(按最新时间输出

根据最新信息发送的时间与现在的时间比较,判断是否大于三十分钟*

@Override
public  Boolean sendSmsTime(Long userId){
   	 List<ProjectSms> list = list(new QueryWrapper<ProjectSms>().lambda()
            .eq(ProjectSms::getUserId,userId)
            .gt(ProjectSms::getSendTime,LocalDateTime.of(LocalDate.now(), LocalTime.MIN))
            .orderByDesc(ProjectSms::getSendTime));
    if(!list.isEmpty()&&list.size()!=0){   //对从数据库拿到的字段判空
        LocalDateTime now =LocalDateTime.now();拿到现在的时间(java8 的时间类)
        LocalDateTime end=list.get(0).getSendTime();拿到list中最新的时间
        Long millis = ChronoUnit.MINUTES.between(end,now);拿到以分钟为单位的差值
        if (millis>30){  
            return true;
        }else {
            return false;
        }
    }else {
        return true;
    }
}
在我们的项目规范中,都是不允许出现魔法值的!所以我们要将间隔时间(30分钟)配置成application中的常量。

application-third.yml中

sms:
  aliyun:
    regionId: 
    accessKeyId: 
    accessSecret: 
    signName:
    intervalTime: 30 #间隔时间单位(分钟)

构建application中的对应类

@ConfigurationProperties(prefix = "sms.aliyun")
@Component
@Data
public class SmsProperties {
    private  String regionId;
    private  String accessKeyId;
    private  String accessSecret;
    private  String signName;
    private  String intervalTime;
}

修改后的时间验证方法

@Override
public  Boolean sendSmsTime(Long userId){
   	 List<ProjectSms> list = list(new QueryWrapper<ProjectSms>().lambda()
            .eq(ProjectSms::getUserId,userId)
            .gt(ProjectSms::getSendTime,LocalDateTime.of(LocalDate.now(), LocalTime.MIN))
            .orderByDesc(ProjectSms::getSendTime));
    if(!list.isEmpty()&&list.size()!=0){
        LocalDateTime now =LocalDateTime.now();
        LocalDateTime end=list.get(0).getSendTime();
        Long millis = ChronoUnit.MINUTES.between(end,now);拿到以分钟为单位的差值
        if (millis > Long.valueOf(smsProperties.getIntervalTime())){
            return true;
        }else {
            return false;
        }
    }else {
        return true;
    }
}

你可能感兴趣的:(java,java,spring,boot,mybatis)