简体   繁体   中英

Update one attribute of an Entity with ModelAttribute

How can I update just one or a few atributes of an Entity with spring form and controller?

Lets say it is User Entity and has id, status, name, address etc... I want to update just name, and address. But when I try to save ather values is null. ı dont want to show all attributes in form logically ( Id, status )

You can use hidden input element to propagate users ID to your view, eg

<input type="hidden" name="user-id" value="${editUserForm.id}">

Put it in a form - when a form is submitted, users ID will also be submitted with it (remember to add ID to your form model). Then retrieve user from database using this ID, set fields you want to set and update it.

EDIT:

Example: your model:

    @Entity
    public class User{
       private Long id;
       private String name;
       private String surname;
       //getters & setters
    }

form you use to edit some of the fields (no surname):

public class UserForm{
         private Long id;
         private String name;
         //getters & setters, constructor
    }

Controller:

 @GetMapping(value="/editUser/{userId}")
    public ModelAndView editUser(@PathVariable Long userId){
    ModelAndView modelAndView = new ModelAndView("editUser");
    User user = // retrieve user from database using userId
    modelAndView.addObject("editUserForm", new UserForm(user));
    return modelAndView;
    }

    @PostMapping(value="/editUser")
    public ModelAndView postEditUser(@ModelAttribute("editUserForm") UserForm editUserForm){
    User userToEdit = //retrive user from database using editUserForm.getId()
    userToEdit.setName(editUserForm.getName());
    //save user to database
    //redirect
    }

Of course logic I presented in controllers should be located in service layer, I just want to give you an idea on what to do.

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