欢迎加qq群:453398542 学习讨论,会定期分享资料课程,解答问题。
今天在做定时任务时,发现通过new Date()生成的时间无法与mybatis返回的Date()做like模糊查询,最后发现mybatis返回的Date()类型数据可以直接与String类型做模糊查询,以下为代码。
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
@Component
@EnableScheduling
@Slf4j
public class ScheduleTaskDeleteWaterquality {
@Autowired
private WatetqualityMapper watetqualityMapper;
@Scheduled(cron = "0 0 0 1/1 * ? ")
public void deleteWaterquality() { //删除30天前的水质数据
Date now=new Date();
String deleteDate=getDeleteDate(now,30);
try{
int effectedNum=watetqualityMapper.deleteByDate(deleteDate);
}catch (Exception e){
log.error("删除30天前的水质数据失败!"+e.getMessage());
}
}
//获取需要删除的时间
public static String getDeleteDate(Date now,int days){
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
calendar.add(calendar.DATE, -days);
Date delete=calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString=sdf.format(delete);
return dateString;
}
}
<!--删除30天前的水质数据-->
<delete id="deleteByDate">
delete from watetquality
where wq_spt like CONCAT(CONCAT('%',#{deleteDate,jdbcType=CHAR}),'%')
</delete>