简体   繁体   English

如何在 java sb 中只允许一个月-年组合

[英]How to allow for only one month-year combination in java sb

How do I allow input for only one month-year combination in Java Spring Boot.如何在 Java Spring Boot. I need to make sure that user (postman client) can input one recording (randomly generated value) per month of that year.我需要确保用户(邮递员客户端)可以在当年的每个月输入一个记录(随机生成的值)。 So for example: month: February -> Year: 2020 -> generatedValue = something random .因此,例如:月:二月 -> 年:2020 -> generatedValue = something random And when user goes to input February 2020 again it throws an exception.当用户再次输入 February 2020 时,它会抛出异常。 I've tried with storing years and months in seperate lists, to check if there's month with that year already present in the database, but to no avail.我试过将年份和月份存储在单独的列表中,以检查数据库中是否已经存在该年份的月份,但无济于事。 In RecordService in first if I'm trying to see if there isn't present year that user entered.如果我试图查看是否没有用户输入的当前年份,首先在 RecordService 中。 For example if there is not a year 2021 then the "if" should add that year to a list so i can check the month-year combo.例如,如果没有 2021 年,那么“如果”应该将该年添加到列表中,以便我可以检查月-年组合。 It works, but not what I need because the second if always throws a RuntimeException(), except when I enter a year that hasn't been entered (for example there are years 2020, 2021 and 2022 but there isn't a year 2023, so when user adds for example:它有效,但不是我所需要的,因为第二个 if 总是抛出 RuntimeException(),除非我输入了一个尚未输入的年份(例如,有 2020、2021 和 2022 年,但没有 2023 年,所以当用户添加例如:

{
    "month": "March",
    "year": "2023",
    "readingTime": "1"
}

the code will work because there isn't a year 2023 in the list, but as soon as they try to enter该代码将起作用,因为列表中没有 2023 年,但是一旦他们尝试输入

{
    "month": "May",
    "year": "2023",
    "readingTime": "1"
}

it will not work because the year is already present, even tho it should because there isn't may-2023 combo in the db.它不会起作用,因为年份已经存在,即使它应该起作用,因为数据库中没有 may-2023 组合。 I've tried to have a boolean to check if the combo exists, but that doesn't make any sense to me.我试过使用 boolean 来检查组合是否存在,但这对我来说没有任何意义。 So please, please help:) Here is my code.所以,请帮助:)这是我的代码。

RecordController.java记录控制器.java

@PostMapping("/{client_id}")
    public Record add(@PathVariable Long client_id, @RequestBody Record record){
        return recordService.add(client_id, record);
    }

RecordService.java记录服务.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;
    }

Record.java记录.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 & month-year functions RandomGenerateValue & month-year 函数

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

Keep year & month together, as a single value将年和月放在一起,作为一个值

Your problem seems to stem from thinking of the year and the month as separate values.您的问题似乎源于将年份和月份视为不同的值。 Instead, combine them.相反,将它们结合起来。 Think in terms of year-month, a single unit.考虑年月,一个单位。

YearMonth class YearMonth

Java includes a class for this concept. Java 包括这个概念的 class。 Its name is appropriate: YearMonth , in the java.time package.它的名字是合适的: YearMonth ,在java.time package。

YearMonth ym = YearMonth.of ( 2023 , 3 ) ;

Or use the Month enum, to ensure valid values.或者使用Month枚举,以确保有效值。

YearMonth ym = YearMonth.of ( 2023 , Month.MARCH ) ;

You can represent your slots for each month and year by using a Map .您可以使用Map代表每个月和每年的插槽。 Keep the keys in sorted order by using a NavigableMap .使用NavigableMap保持键的排序顺序。

NavigableMap< YearMonth , UUID > map = new TreeMap<>() ;
map.put( 
    YearMonth.of ( 2023 , Month.MARCH ) , 
    UUID.randomUUID()
);
map.put( 
    YearMonth.of ( 2023 , Month.FEBRUARY ) , 
    UUID.randomUUID()
);

Test if a value has already been put.测试一个值是否已经被放置。

boolean alreadyPut2023March = map.containsKey( YearMonth.of ( 2023 , Month.MARCH ) ) ;

ISO 8601国际标准化组织 8601

For text purposes, use standard ISO 8601 format: YYYY-MM出于文本目的,请使用标准ISO 8601格式:YYYY-MM

The java.time classes use ISO 8601 formats by default when parsing/generating text. java.time类在解析/生成文本时默认使用 ISO 8601 格式。

String iso8601Output = YearMonth.of ( 2023 , Month.MARCH ).toString() ;

2023-03 2023-03

Such a string could be used for storage in your database, assuming your database does not offer a year-month data type.假设您的数据库不提供年-月数据类型,这样的字符串可用于存储在您的数据库中。 I don't know of any database that does offer such a data type.我不知道有任何数据库提供这种数据类型。 So text will suffice.所以文字就足够了。

Notice that when sorted alphabetically, the values are also sorted chronologically.请注意,当按字母顺序排序时,值也会按时间顺序排序。

Your JSON would look like this:您的 JSON 将如下所示:

{
    "year-month": "2023-03",
    "readingTime": "1"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM