简体   繁体   中英

Mathematical operations in Java Spring boot with services

I want to add two columns and place the result in the third. My table conrains 100+ line.

My model: 在此处输入图像描述 My repository:

    import java.util.List;
    @Repository
    public interface OilRepo extends JpaRepository<OilModel,Long> {
    }

Controller:

        @RestController
    @RequestMapping()
    public class OilController {
    
        @Autowired
        private OilService oilService;
    
        @GetMapping(value = "/all")
        public List<OilModel> oilModels() { return oilService.getOilModel();}
    
        @PostMapping(value = "/save")
        public List<OilModel> oilModel(@RequestBody List<OilModel> oilModel){
            return oilService.saveOil(oilModel); }
    }

and Services

import java.util.List;

@Service
public class OilService {
@Autowired
private OilRepo oilRepo;

public List<OilModel> getOilModel() { return oilRepo.findAll(); }
public List<OilModel> saveOil(List<OilModel> oilModels){
    oilModels.stream().map(oilModel -> oilModel.average = 
oilModel.getO_ai_92()+oilModel.getO_ai_95());
    return oilRepo.saveAll(oilModels);

}

}

How can I write the service correctly to make this code work?

You can do it inside getAverage() method as shown below:-

public class OilModel {

    @Access(AccessType.PROPERTY)
    private double average;
    
    ...
    ...
    ...

    public Double getAverage() {
        return get0_ai_92() + get0_ai_95();
    }
}

and store the list directly without doing any operations on it.

Note:- make sure to add @Access(AccessType.PROPERTY) on average field to allow jpa access the value from the method, not from the field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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