java—从日期格式早于x小时或秒的数据库中检索项

2admgd59  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(358)

我有一个cronjob,需要通过condition子句从db获取一些项。在这种情况下,我需要比较一些日期的时间,它们就像数据库中的(fri-dec 18 12:36:07 eet 2020)(java.util.date)。当执行查询时,我需要从数据库中检索到比当前时间早1小时的项。
我想我的问题应该是 select * from table_name where date_column > int_variable. 问题是变量是一个从别处设置的整数。我该怎么做?我需要把变量从int改成别的吗?我以我的班级为例。在我的课堂上,我还没有上面写的示例查询。谢谢!

public class HttpSessionCleanJob extends AbstractJobPerformable<HttpSessionCleanJobModel> {

private static final Logger LOG = Logger.getLogger(HttpSessionCleanJob.class.getName());

@Resource
private ModelService modelService;
@Resource
private FlexibleSearchService flexibleSearchService;

@Override
public PerformResult perform(final HttpSessionCleanJobModel httpSessionCleanJobModel) {

    LOG.info("Start cleaning StoredHttpSession items...");
    final int maxJobTime = httpSessionCleanJobModel.getTime();

    final String queryString = "SELECT {" + StoredHttpSessionModel.PK + "} FROM {" + StoredHttpSessionModel._TYPECODE + "}";

    final Date specificTime = new Date();
    final FlexibleSearchQuery query = new FlexibleSearchQuery(queryString, Collections.singletonMap("specificTime", specificTime));

    final SearchResult<StoredHttpSessionModel> searchResult = flexibleSearchService.search(query);

    List<StoredHttpSessionModel> assetModelList = searchResult.getResult();

    for(StoredHttpSessionModel storedHttpSessionModel : assetModelList) {
        LOG.info(storedHttpSessionModel.getModifiedtime());
    }

    LOG.info("Finished cleaning StoredHttpSession items...");
    return new PerformResult(CronJobResult.SUCCESS, CronJobStatus.FINISHED);
}
}
eoigrqb6

eoigrqb61#

我用以下方法解决了这个问题:

final String queryString = "SELECT {" + StoredHttpSessionModel.PK + "} FROM {" + StoredHttpSessionModel._TYPECODE + "} WHERE {" + StoredHttpSessionModel.MODIFIEDTIME +"} < now() - interval ?maxJobTime SECOND";
dw1jzc5e

dw1jzc5e2#

您可以尝试以下方法:

specificTime.setTime(specificTime.getTime() - 5000)

结果是当前日期减去5000毫秒(5秒)。
然后:

final String queryString = "SELECT {" + StoredHttpSessionModel.PK + "} FROM {" + StoredHttpSessionModel._TYPECODE + "} WHERE {modifiedTime} < ?specificTime";

 final Date specificTime = new Date();
 final FlexibleSearchQuery query = new FlexibleSearchQuery(queryString, Collections.singletonMap("specificTime", specificTime));

这将检索所有 StoredHttpSessionModel 修改日期超过5秒,
使代码更符合您的需要。

相关问题