由功能到接口,该怎么写—— 一个实例

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

需求描述:

网元健康度的表 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写成的小接口就完成啦!

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值