0

User Entity

@Entity
    public class User {
        @Id
        @Email
        @NotEmpty
        @Column(unique = true)
        private String email;
        @NotEmpty
        private String name;
        @Size(min=4)
        private String password;
        @OneToMany(mappedBy = "user",cascade = CascadeType.ALL)
        private List<Task> tasks;
        @ManyToMany(cascade = CascadeType.ALL)
        @JoinTable(name="USER_ROLES",joinColumns = {
                @JoinColumn(name="USER_EMAIL",referencedColumnName = "email")
        },inverseJoinColumns = {@JoinColumn(name="ROLE_NAME",referencedColumnName = "name")})
        private List<Role> roles;

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public List<Task> getTasks() {
            return tasks;
        }

        public void setTasks(List<Task> tasks) {
            this.tasks = tasks;
        }

        public List<Role> getRoles() {
            return roles;
        }

        public void setRoles(List<Role> roles) {
            this.roles = roles;
        }

How can I make this edit controller method work? Is it even possible to change the Id of the Entity? I have an HTML form and want to update email and password trough it.

@GetMapping(value = "/admin/setDetails")
public String editUser(@RequestParam("email") String email, Model model){
    User user = userService.findOne(email);
    model.addAttribute("user",user);
    return "setdetails";
}

I also tried to do it with userRepository.save(user) but whenever I edited email it makes new user and whenever I changed password I could not log in anymore with any password.

krishna Prasad
  • 2,695
  • 1
  • 23
  • 38
pes
  • 3
  • 4

2 Answers2

0

you have to pass email id which is present in DB. If you userRepository.save(user) with valid email then it should update user info.

second approach is you can user update method as below

    @Modifying
    @Transactional
    @Query("update User u set u.password = :#{#user.password} where u.email = :#{#user.email}")
    int updateInfo(@Param("user") User user);
Jaganath Kamble
  • 326
  • 1
  • 9
0

First of all, if you want to update an existing entity you have to expose a PUT or PATCH API depending on which kind of update you want to provide (it seems like PATCH in your case).

You can follow Jaganath's answer in case you need to update only several fields in your entity. Otherwise, please read this answer, it will give you more flexible way of the update.

Stepan Tsybulski
  • 839
  • 6
  • 16