首页 > 解决方案 > 缺少值 Spring-Boot RestController

问题描述

我对 post 方法有疑问。当我想发送一些数据时,缺少 1 个值,就像这张图片中一样:

图片

如您所见,未添加 rNumber。

这是模拟实体(该实体将存储数据)

@Entity
@Table(name = "Simulation")
@Getter
@Setter
@NoArgsConstructor
public class Simulation extends BaseEntity
{
    @Column(name = "name", length = 25, unique = true)
    private String name;
    @Column(name = "population_count")
    private long populationCount;
    @Column(name = "initial_infected_number")
    private long initialInfectedNumber;
    @Column(name = "r_number")
    private double rNumber;
    @Column(name = "mortality_rate")
    private double mortalityRate;
    @Column(name = "disease_duration")
    private int diseaseDuration;
    @Column(name = "time_of_dying")
    private int timeOfDying;
    @Column(name = "days_of_simulation")
    private int daysOfSimulation;
    @Column(name = "protection_duration")
    private int protectionDuration;
    @OneToMany(mappedBy = "simulation", cascade = CascadeType.ALL)
    private List<Record> records;

    public Simulation(String name, long populationCount,
                      long initialInfectedNumber, double rNumber,
                      double mortalityRate, int diseaseDuration,
                      int timeOfDying, int daysOfSimulation,
                      int protectionDuration) throws SimulationCreationException
    {
        this.name = name;
        this.populationCount = populationCount;
        this.initialInfectedNumber = initialInfectedNumber;
        this.rNumber = rNumber;
        this.mortalityRate = mortalityRate;
        this.diseaseDuration = diseaseDuration;
        this.timeOfDying = timeOfDying;
        this.daysOfSimulation = daysOfSimulation;
        this.protectionDuration = protectionDuration;

        validate();
    }

    private void validate() throws SimulationCreationException
    {
        if (populationCount < initialInfectedNumber)
            throw new SimulationCreationException("The initial number of infected must not exceed the number of the population");
        if (rNumber < 0.0)
            throw new SimulationCreationException("R number cannot be negative");
        if (mortalityRate < 0.0 || mortalityRate > 1.0)
            throw new SimulationCreationException("Mortality rate must be between 0 and 1");
        if (populationCount < initialInfectedNumber)
            throw new SimulationCreationException("Infected number cannot exceed the number of population");
        if (timeOfDying > diseaseDuration)
            throw new SimulationCreationException("Healthy person cannot die of a disease");
    }

    public void createRecords()
    {
        List<Record> records = new ArrayList<>();
        records.add(initialRecord());

        /*
        Arrays that store information about how many ppl got sick
        The for loop will use dynamic programming
         */
        long[] sickPeopleWaitingForRecovery = new long[diseaseDuration];
        long[] sickPeopleWaitingForDeath = new long[timeOfDying];
        long[] resistancePeopleProtectionDuration = new long[protectionDuration];

        sickPeopleWaitingForDeath[0] = Math.round(initialInfectedNumber * mortalityRate);
        sickPeopleWaitingForRecovery[0] = initialInfectedNumber - sickPeopleWaitingForDeath[0];

        boolean areAnyRestrictions = false;

        for (int i=1 ; i<daysOfSimulation ; i++)
        {
            long infectedCount = records.get(i-1).getInfectedCount();
            long susceptibleToInfection = records.get(i-1).getSusceptibleToInfection();
            long deathCount = records.get(i-1).getDeathCount();
            long resistantCount = records.get(i-1).getResistantCount();
            int sickPeopleWaitingForRecoveryIndex = i%diseaseDuration;
            int sickPeopleWaitingForDeathIndex = i%timeOfDying;
            int resistancePeopleProtectionDurationIndex = i%protectionDuration;

            long newInfectedNumber = Math.round(rNumber * infectedCount) - infectedCount;
            if (newInfectedNumber > susceptibleToInfection)
                newInfectedNumber = susceptibleToInfection;

            /*
            Too many new infected
            New restrictions incoming
            */
            if (newInfectedNumber > 0.01 * populationCount && !areAnyRestrictions) {
                rNumber /= 3;
                areAnyRestrictions = true;
            }

            /*
            People think that they don't need restrictions anymore
            R number back to previous value
            */
            if (newInfectedNumber < 0.001 * populationCount && areAnyRestrictions) {
                rNumber *= 3;
                areAnyRestrictions = false;
            }

            resistantCount -= resistancePeopleProtectionDuration[resistancePeopleProtectionDurationIndex];
            susceptibleToInfection += resistancePeopleProtectionDuration[resistancePeopleProtectionDurationIndex];

            resistantCount += sickPeopleWaitingForRecovery[sickPeopleWaitingForRecoveryIndex];
            infectedCount -= sickPeopleWaitingForRecovery[sickPeopleWaitingForRecoveryIndex];

            deathCount += sickPeopleWaitingForDeath[sickPeopleWaitingForDeathIndex];
            infectedCount -= sickPeopleWaitingForDeath[sickPeopleWaitingForDeathIndex];

            resistancePeopleProtectionDuration[resistancePeopleProtectionDurationIndex] = sickPeopleWaitingForRecovery[sickPeopleWaitingForRecoveryIndex];
            sickPeopleWaitingForDeath[sickPeopleWaitingForDeathIndex] = Math.round(newInfectedNumber * mortalityRate);
            sickPeopleWaitingForRecovery[sickPeopleWaitingForRecoveryIndex] = newInfectedNumber - sickPeopleWaitingForDeath[sickPeopleWaitingForDeathIndex];

            infectedCount += newInfectedNumber;
            susceptibleToInfection -= newInfectedNumber;
            records.add(new Record(
                    infectedCount,
                    susceptibleToInfection,
                    deathCount,
                    resistantCount,
                    this
            ));
        }
        this.records = records;
    }

    private Record initialRecord()
    {
        return new Record(initialInfectedNumber,
                populationCount - initialInfectedNumber,
                0,
                0,
                this);
    }

    @Override
    public String toString() {
        return "Simulation{" +
                "name='" + name + '\'' +
                ", populationCount=" + populationCount +
                ", initialInfectedNumber=" + initialInfectedNumber +
                ", rNumber=" + rNumber +
                ", mortalityRate=" + mortalityRate +
                ", diseaseDuration=" + diseaseDuration +
                ", timeOfDying=" + timeOfDying +
                ", daysOfSimulation=" + daysOfSimulation +
                ", protectionDuration=" + protectionDuration +
                '}';
    }
}

和控制器类:

@RestController
@RequestMapping("/simulation")
public class SimulationController
{
    @Autowired
    SimulationService simulationService;

    @PostMapping
    public SimulationDTO addSimulation(@RequestBody Simulation simulation)
    {
        System.out.println(simulation);
        simulation.createRecords();
        return new SimulationDTO(simulationService.save(simulation));
    }

    @GetMapping("/all")
    @ResponseBody
    public List<SimulationDTO> getAll()
    {
        List<SimulationDTO> simulationDTOs = new ArrayList<>();

        for(Simulation simulation : simulationService.findAll())
            simulationDTOs.add(new SimulationDTO(simulation));

        return simulationDTOs;
    }

    @GetMapping
    @ResponseBody
    public SimulationDTO getByName(@RequestBody String name)
    {
        return new SimulationDTO(simulationService.findByName(name));

    }
}

在更改为 DTO 之前,此值设置为 0,但如果您想要这里是 DTO 类:

@Data
@Component
@AllArgsConstructor
@NoArgsConstructor
public class SimulationDTO {
    String name;
    private long populationCount;
    private long initialInfectedNumber;
    private double rNumber;
    private double mortalityRate;
    private int diseaseDuration;
    private int timeOfDying;
    private int daysOfSimulation;
    private int protectionDuration;
    private List<RecordDTO> recordDTOs;

    public SimulationDTO(Simulation simulation)
    {
        this.name = simulation.getName();
        this.populationCount = simulation.getPopulationCount();
        this.initialInfectedNumber = simulation.getInitialInfectedNumber();
        this.rNumber = simulation.getRNumber();
        this.mortalityRate = simulation.getMortalityRate();
        this.diseaseDuration = simulation.getDiseaseDuration();
        this.timeOfDying = simulation.getTimeOfDying();
        this.daysOfSimulation = simulation.getDaysOfSimulation();
        this.protectionDuration = simulation.getProtectionDuration();
        this.recordDTOs = new ArrayList<>();

        for (Record record : simulation.getRecords())
            recordDTOs.add(new RecordDTO(record));
    }
}

我想问你在这种情况下我能做些什么。我尝试向这个变量添加 JsonProperty 注释,但没有帮助。感谢您的回答。

标签: javaspring-boothttpspring-mvcpost

解决方案


我假设您的问题是,为什么在请求有效负载中不存在此字段时将其设置为 0。

对此的简单答案和解决方案是,因为您使用的是原语,所以它们具有默认值。您可以在此处查看原语列表及其默认值:https ://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html 。将双打切换为 Double,将 int 切换为 Integer,将 long 切换为 Long。


推荐阅读