需求描述:
网元健康度的表 DEVICE_HEALTH,记录了id,timeStamp(时间点),deviceName(网元名),A,B,C,D,E,F六个影响网元健康度的影响因素对健康度造成的程度(结果是评分,分数大小表示影响程度)。数据不连续,离散,间隔5分钟。
现在给定一个时间(beforeTime),写一个接口,实现查询这个时间点前最新的一个时间点的数据。用到技术:JPA
分析:
(1)单表查询,利用jpa关键字就可以;
(2)先查距离最近的那个时间点,再查这个时间点的数据
代码:
表对应的实体类,entity
@Data
@Entity
@Table(name="DEVICE_HEALTH")
public class DeviceHealthEntity {
@Id
private String id; // 网元健康度ID
private String deviceName; // 网元名称
private Double points; // 得分
@Column(name="A")
private Double alarmPoints; // 告警扣分
@Column(name="B")
private Double kpiPoints; // 性能扣分
@Column(name="C")
private Double logPoints; // 日志扣分
@Column(name="D")
private Double projectPoints; // 工程扣分
@Column(name="E")
private Double dialPoints; // 拨测扣分
@Column(name="F")
private Double complaintPoints; // 投诉扣分
private Date timeStamp; // 时间点
}
repository层
public IntFace DeviceHealthRepository extends JpaRepository<DeviceHealthEntity,String>,JpaSpecificationExecutor<DeviceHealthEntity>{
DeviceHealthEntity findFirstByTimeStampOrderByTimeStampDesc(Date timeStamp);
List<DeviceHealthEntity> findByTimeStamp(Date timeStamp);
}
Service层
@Slf4J
@Service
public class DeviceHealthService{
@Autowired
private DeviceHealthRepository deviceHealthRepository;
public List<DeviceHealthEntity> getDeviceHealth(Date beforeTime){
DeviceHealthEntity entity = deviceHealthRepository.findFirstByTimeStampBeforeOrderByTimeStampDesc(beforeTime);
//养成习惯,对结果进行判断
if(null == entity) {
log.info("getDeviceHealth >> 在{} 这个时间点前,没有相关网元信息",beforeTime);
//success算是一个构造方法,除了将data信息加进去外,还会有其他附加信息,看需求而定
return ResultWithData.success(newArrayList());
}
return ResultWithData.success(deviceHealthRepository.findByTimeStamp(entity.getTimeStamp()));
}
}
关于ResultWithData这个范式截图:

controller层:
@Slf4j
@RestController
public class DeviceHealthRestController{
@Autowired
private DeviceHealthService deviceHealthService;
@RequestMapping("/list")
public List<DeviceHealthEntity> getDeviceHealth(Date beforeTime){
//养成习惯对入参进行判断
if(null == beforeTime){
log.info("getDeviceHealth >> 未传入正确的时间点");
beforeTime = new Date();
}
log.info("getDeviceHealth >> beforeTime = {}",beforeTime);
return deviceHealthService.getDeviceHealth(beforeTime);
}
}
至此,这个 Jpa写成的小接口就完成啦!

本文介绍了一个使用JPA技术实现的接口,该接口能够查询指定时间前最新的网元健康度数据。网元健康度由六个因素评估,数据记录于DEVICE_HEALTH表中,接口通过查询最近时间点的数据来返回网元的健康状况。
6718

被折叠的 条评论
为什么被折叠?



