jpa + mongodb 最近24小时时间范围查询

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);

}

JPA命名规则参考

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);
    }`
    
}

猜你喜欢

转载自blog.csdn.net/qq_37242224/article/details/87920944
今日推荐