Spring Data JPA - 在日期之前和之后构建查询

8
我是Java JPA - Spring Boot的新手。我想创建一个JPA查找,以计算两个日期之间的行数。
我需要获取一个数字,显示在过去28天内加入的成员数量。就像10这样。
但也要获得一个值,表示与上个月的差异——所以+4%——或-2%——所以我想它将是一个count1/count2 * 100 = difference。你如何检测极性——所以评估它是否为负或正?
目前我有类似这样的东西
long countByRegisteredDateAfter(Date thresholdDate) throws Exception;

但可能需要更像这样的东西。
long countByRegisteredBeforeDateAfter(Date thresholdDate1, Date thresholdDate2)
    throws Exception;

也许还有更加精细调整的内容,就像这样

long countByRegisteredBeforeAndDateAfterAndRole(Date thresholdDate1, Date thresholdDate2, String role)
    throws Exception;

到目前为止的代码:

            // 28 days ago
            Calendar thresholdPast28 = Calendar.getInstance();
            thresholdPast28.set(Calendar.HOUR_OF_DAY,0);
            thresholdPast28.set(Calendar.MINUTE,0);
            thresholdPast28.set(Calendar.SECOND,0);
            thresholdPast28.add(Calendar.DATE,-28);

            java.util.Date thresholdPast28Date = thresholdPast28.getTime();
            Long countLast28Days = (Long) tblLoginRepository.countByRegisteredDateAfter(thresholdPast28Date);

            System.out.println("countLast28Days " + countLast28Days);


            // 56 days ago
            Calendar thresholdPast56 = Calendar.getInstance();
            thresholdPast56.set(Calendar.HOUR_OF_DAY,0);
            thresholdPast56.set(Calendar.MINUTE,0);
            thresholdPast56.set(Calendar.SECOND,0);
            thresholdPast56.add(Calendar.DATE,-28);

            java.util.Date thresholdPast56Date = thresholdPast56.getTime();
            Long countLast56Days = (Long) tblLoginRepository.countByRegisteredDateAfter(thresholdPast56Date);

            System.out.println("countLast56Days " + countLast56Days);
1个回答

16

我有点困惑,因为主题说明你想在之前和之后尝试找到日期,而后面你又希望它们在之间。不过,要获取之间的日期,请尝试:

long countByRegisteredDateBetween(Date thresholdDate1, Date thresholdDate2)

或者在第二个例子中

long countByRegisteredDateBetweenAndRole(Date thresholdDate1, Date thresholdDate2, String role)

要获取前后内容,可以尝试以下方法:

long countByRegisteredDateBeforeAndRegisteredDateAfter(Date thresholdDate1, Date thresholdDate2)

类似于Role案件的处理方式


谢谢@pezetem - 我也刚想到这个解决方案。 - The Old County

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接