Mybatis-Plus按昨天、今天、明天、近?天,自定义起始时间查询
1. 前端需要
2. 后端 0SQL 实现
实体类主要字段:
public class DemoEntity implements Serializable {
private static final long serialVersionUID = 1L;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty("创建时间")
private Date createTime;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty("更新时间")
private Date updateTime;
/**
* 查询时间
*/
@TableField(exist = false)
@ApiModelProperty(value = "查询类型:1-今天,2-昨天,3-近?天,4-自定义起止时间")
private Integer queryType;
@TableField(exist = false)
@ApiModelProperty(value = "queryType为3时指定的天数")
private Integer queryDay;
@TableField(exist = false)
@ApiModelProperty(value = "queryType为4时的起始时间")
private Date queryStartTime;
@TableField(exist = false)
@ApiModelProperty(value = "queryType为4时的结束时间")
private Date queryEndTime;
}
service的实现代码:
QueryWrapper<DemoEntity> queryWrapper = new QueryWrapper<>();
// 添加时间(查询类型:1-今天,2-昨天,3-近?天,4-自定义起止时间)
if (entity.getQueryType()!= null) {
switch (entity.getQueryType()) {
case 1:
queryWrapper.apply(true, "TO_DAYS(NOW())-TO_DAYS(create_time) = 0");
break;
case 2:
queryWrapper.apply(true, "TO_DAYS(NOW())-TO_DAYS(create_time) = 1");
break;
case 3:
queryWrapper.apply(true, "DATE_SUB(CURDATE(), INTERVAL "+ entity.getQueryDay() +" DAY) <= date(create_time)");
break;
case 4:
java.text.DateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String startTime = sdf.format(entity.getQueryStartTime());
String endTime = sdf.format(entity.getQueryEndTime());
queryWrapper.apply(true, "create_time between '"+ startTime +"' and '" + endTime + "'");
break;
}
}