I want to modify an existing user object in the database (retrieved using its id) via a @RequestBody (Spring Boot). Unfortunately, my object is found, but all String values are replaced by a null type. When I display the data I'm supposed to receive, everything is null.
Model
@Entity
@Table(name="user")
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
@Getter
@Setter
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id", nullable = false, updatable = false)
private Long id;
@Column
private String name;
@Column
private String email;
@Column
private String password;
@Column
private String role;
@Column
private double somme_dispo;
}
Controller
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fan2foot.fan2foot.repository.UserRepository;
import com.fan2foot.fan2foot.service.UserService;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import com.fan2foot.fan2foot.model.User;
@PutMapping("/update/{id}")
public ResponseEntity<User> update(@PathVariable Long id, @RequestBody User user) {
System.out.println(user.getName());
System.out.println(user.getEmail());
System.out.println(user.getPassword());
System.out.println(user.getRole());
User users = userService.updateUser(id, user);
System.out.println(users.getName());
System.out.println(users.getEmail());
System.out.println(users.getPassword());
System.out.println(users.getRole());
return new ResponseEntity<>(users, HttpStatus.OK);
}
Service
public User updateUser(Long id, User user) {
return userRepository.findById(id)
.map(u -> {
u.setName(user.getName());
u.setEmail(user.getEmail());
u.setPassword(user.getPassword());
u.setRole(user.getRole());
u.setSomme_dispo(user.getSomme_dispo());
return userRepository.save(u);
}).orElseThrow(() -> new RuntimeException("User non trouvé..."));
}
Here is how I send data in postman
Here is the result of the query execution
With another guy we inspected the model, controller, service and concluded that we have exactly the same code, his code works but mine doesn't
Check the @RequestBody import,
I think this import making issue
import io.swagger.v3.oas.annotations.parameters.RequestBody;
Use this import
import org.springframework.web.bind.annotation.RequestBody;