Home > Software design >  How to save data immediately to the database using Spring Boot and JPA Repository
How to save data immediately to the database using Spring Boot and JPA Repository

Time:11-03

I am trying to save some data into the database using save from JPA Repository. I have the call to save method in another method. The problem is that the entity created is not saved after .save() is called. I have to access the index from the saved data but because the mentioned data is not saved I get "Index -1 out of bounds for length 0". After this, I think it rolles back because the execution continues. The code is the following:

    public void method(Double number, Integer entityId){
        Entity entity= findById(entityId);

        CalculatedValue calculatedValue= new CalculatedValue ();
        LocalDateTime dateTime = LocalDateTime.now();
        monitoredValue.setDateTime(dateTime);

        List<CalculatedValue > calculatedValueList= calculatedValueservice.findAllById(entityId);

        if(calculatedValueList.isEmpty()){
            calculatedValue.setValue(0.0);
            calculatedValue.setEntity(entity);
            calculatedValueRespository.save(calculatedValue);
            
        }


        CaclulatedValue lastCalculatedValue = calculatedValueList.get(calculatedValueList.size() - 1);
}

My question is: how do I save the calculatedValue to the database in such way that I can have elements in the lastCalculatedValue list and access their indexes?

CodePudding user response:

Your list will not be updated automatically. You have to add the new element manually

List<CalculatedValue > calculatedValueList= calculatedValueservice.findAllById(entityId);

        if(calculatedValueList.isEmpty()){
            calculatedValue.setValue(0.0);
            calculatedValue.setEntity(entity);
            calculatedValueRespository.save(calculatedValue);
            // ADD IT MANUALLY
            calculatedValueList.add(calculatedValue)
        }
  • Related