如何在 Java Spring Boot 中仅允许输入一个月-一年的组合。我需要确保用户(邮递员客户端)可以在当年每月输入一个记录(随机生成的值)。例如:月份:二月 -> 年:2020 -> generatedValue = 随机的。当用户再次输入 2020 年 2 月时,它会抛出异常。我尝试过将年份和月份存储在单独的列表中,以检查数据库中是否已存在该年份的月份,但无济于事。首先在 RecordService 中,如果我想查看是否没有用户输入的当前年份。例如,如果没有 2021 年,那么“if”应该将该年份添加到列表中,以便我可以检查月年组合。它有效,但不是我需要的,因为第二个 if 总是抛出 RuntimeException() ,除非我输入尚未输入的年份(例如有 2020 年、2021 年和 2022 年,但没有 2023 年) ,因此当用户添加时:
{
"month": "March",
"year": "2023",
"readingTime": "1"
}
该代码将起作用,因为列表中没有 2023 年,但只要他们尝试输入
{
"month": "May",
"year": "2023",
"readingTime": "1"
}
它不会工作,因为年份已经存在,即使它应该工作,因为数据库中没有 2023 年 5 月的组合。我尝试使用布尔值来检查组合是否存在,但这对我来说没有任何意义。所以请大家帮忙:) 这是我的代码。
RecordController.java
@PostMapping("/{client_id}")
public Record add(@PathVariable Long client_id, @RequestBody Record record){
return recordService.add(client_id, record);
}
RecordService.java
public Record add(Long client_id, Record record){
List<String> monthList = months();
List<Integer> yearList = years();
Record recordSave = new Record();
recordSave.setId(client_id);
recordSave.setYear(record.getYear());
recordSave.setMonth(record.getMonth());
recordSave.setReadingTime(record.getReadingTime());
recordSave.setReadingValue(randomGenerate());
//Does not work
if (!yearList.contains(recordSave.getYear())){
yearList.add(recordSave.getYear());
}
//Does not work
if (monthList.contains(recordSave.getMonth()) && yearList.contains(recordSave.getYear())){
throw new RuntimeException();
}
else {
recordRepository.save(recordSave);
}
return null;
}
记录.java
@Data
@Entity
@Table(name = "record")
@JsonIgnoreProperties({"hibernateLazyInitializer","handler","device"})
public class Record implements Serializable {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
String month;
Integer year;
String readingTime;
Float readingValue;
boolean isPresent;
}
RandomGenerateValue 和月年函数
public Float randomGenerate(){
int max = 105, min = 14;
float random_float = (float)Math.floor(Math.random()*(max-min+1)+min);
return random_float;
}
public List<String> months(){
List<String> monthList = new ArrayList<>();
monthList.add("January"); monthList.add("February"); monthList.add("March"); monthList.add("April");
monthList.add("May"); monthList.add("June"); monthList.add("July"); monthList.add("August");
monthList.add("September"); monthList.add("October"); monthList.add("November"); monthList.add("December");
return monthList;
}
public List<Integer> years(){
List<Integer> yearList = new ArrayList<>();
yearList.add(2020);
yearList.add(2021);
return yearList;
} Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号