Search code examples
spring-boothibernatethymeleaf

while updating specific attributes of an Entity other attributes getting null values


this is my controller class i have new window and edit window. In new window suppose i have 6 fields so when i fill all the values and click on save button the values are getting stored in database, and in edit window i have 4 fields out of those 6 fields i just want to edit these 4 fields but when i edit those 4 fields other fields getting null values means the fields which i don't want to edit they filled with null values previous values overwriiten by null values

@RequestMapping("/newbin")
public String showNewBinForm(Model model) {
    Bin bin=new Bin();
    model.addAttribute("bin",bin);
    List<Warehouse> warehouseDetails= wservice.listAll();
     model.addAttribute("warehouseDetails",warehouseDetails);
    return "new_bin";
}

@RequestMapping(value = "/savebin", method = RequestMethod.POST)
    public String saveBin(@ModelAttribute("bin") Bin bin) {
    
        service.save(bin);
        return "redirect:binwindow";
    }

@RequestMapping("/editbin/{id}")
public String showEditBinPage(@PathVariable(name = "id") Long id,Model model) {
    Bin bin = service.get(id);
model.addAttribute("bin", bin);
return "edit_bin";
}

Service-

[public class BinService {
         
        @Autowired
        private BinRepository repo;
         
        public List<Bin> listAll() {
            return repo.findAll();
        }
         
        public void save(Bin bin) {
            repo.save(bin);
        }
         
        public Bin get(long id) {
            return repo.findById(id).get();
        }

Solution

  • I have found the solution of this problem but its quite lengthy if we have more no of fields.

    solution- on the Edit page I have placed all the fields and the fields which i do not want to edit are kept as hidden field so when we click on New button and fill all the required data so the data are getting stored in the Entity class fields (or database) so if we click on edit page we placed the attributes which we want to edit and other attributes as hidden field so on clicking submit button the values which edited are updated in database and the hidden fields contains the values which we have filled on new window page for that particular ID are also stored.