jpa + mongodb 最近24小时时间范围查询
程序员文章站
2022-06-07 13:13:58
...
jpa + mongodb 最近24小时时间范围查询
Entity
@Document("logs")
@Data
@Builder
public class LogEntity implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
private ObjectId id;
private String timestamp; // 使用System.currentTimeMillis()获取时间戳
}
Repository
@Repository
public interface LogRepos extends MongoRepository<LogEntity, ObjectId>
{
/**
* 查询出timestamp大于startTimestamp的数据
*/
List<LogEntity> findByTimestampAfter(String startTimestamp);
}
Controller
@RestController("/log")
public class LogController
{
@Autowired
private LogRepos repos;
@GetMapping("/last{n}Hours")
public List<LogEntity> logsLastNHours(@PathParam("n") int n)
{
Calendar time = Calendar.getInstance();
time.add(Calendar.HOUR_OF_DAY, -n); // 加上负的小时数
String startTimestamp = String.valueOf(time.getTimeInMillis());
return repos.findByTimestampAfter(startTimestamp);
}`
}