用spring boot编写流量计 站点编号 水位保留2位小数, 流速保留2位小数 ,流量保留2位小数以及时间的代码
时间: 2023-09-24 07:05:33 浏览: 177
1. 编写实体类
```java
@Entity
@Table(name = "flow_meter")
public class FlowMeter {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "site_no", nullable = false)
private String siteNo;
@Column(name = "water_level", nullable = false, precision = 2)
private Double waterLevel;
@Column(name = "flow_speed", nullable = false, precision = 2)
private Double flowSpeed;
@Column(name = "flow_rate", nullable = false, precision = 2)
private Double flowRate;
@Column(name = "time", nullable = false)
private LocalDateTime time;
// getter and setter
}
```
2. 编写Repository接口
```java
public interface FlowMeterRepository extends JpaRepository<FlowMeter, Long> {
}
```
3. 编写Service类
```java
@Service
public class FlowMeterService {
private final FlowMeterRepository flowMeterRepository;
public FlowMeterService(FlowMeterRepository flowMeterRepository) {
this.flowMeterRepository = flowMeterRepository;
}
public FlowMeter save(FlowMeter flowMeter) {
return flowMeterRepository.save(flowMeter);
}
public List<FlowMeter> findAll() {
return flowMeterRepository.findAll();
}
public Optional<FlowMeter> findById(Long id) {
return flowMeterRepository.findById(id);
}
public void deleteById(Long id) {
flowMeterRepository.deleteById(id);
}
}
```
4. 编写Controller类
```java
@RestController
@RequestMapping("/flow-meter")
public class FlowMeterController {
private final FlowMeterService flowMeterService;
public FlowMeterController(FlowMeterService flowMeterService) {
this.flowMeterService = flowMeterService;
}
@PostMapping
public FlowMeter save(@RequestBody FlowMeter flowMeter) {
return flowMeterService.save(flowMeter);
}
@GetMapping
public List<FlowMeter> findAll() {
return flowMeterService.findAll();
}
@GetMapping("/{id}")
public Optional<FlowMeter> findById(@PathVariable Long id) {
return flowMeterService.findById(id);
}
@DeleteMapping("/{id}")
public void deleteById(@PathVariable Long id) {
flowMeterService.deleteById(id);
}
}
```
5. 配置数据库
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/flow_meter?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
database-platform: org.hibernate.dialect.MySQL8Dialect
hibernate:
ddl-auto: update
show-sql: true
```
6. 运行程序
启动Spring Boot应用程序后,可使用Postman或其他工具测试API。例如,要保存流量计数据:
```
POST http://localhost:8080/flow-meter
{
"siteNo": "001",
"waterLevel": 1.23,
"flowSpeed": 4.56,
"flowRate": 7.89,
"time": "2021-09-01T10:00:00"
}
```
要获取所有流量计数据:
```
GET http://localhost:8080/flow-meter
```
要获取特定ID的流量计数据:
```
GET http://localhost:8080/flow-meter/1
```
要删除特定ID的流量计数据:
```
DELETE http://localhost:8080/flow-meter/1
```
阅读全文