Reputation: 149
I'm new at Java and trying to understand how MVC architecture goes. Forgive me if I'm wasting your time. I wrote a DAO Service, it handles the crud model (get, read, update, delete).
public List<User> getUsers();
public User getUser(Long userId);
public void createUser(User user);
public void updateUser(User user);
public void delete(Long userId);
}
here are my abstract DAO functions.
@Override
@Transactional
public void updateUser(User user) {
em.merge(user);
}
and the controller:
@PutMapping(value = "/{userId}", produces = "application/json")
public ResponseEntity<UserDTO> update(@PathVariable Long userId, @RequestBody UserDTO user){
try{
service.updateUser(user);
return new ResponseEntity<>(HttpStatus.OK);
} catch (HttpClientErrorException p){
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} catch (HttpServerErrorException.InternalServerError u){
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
in the service:
@Override
public void updateUser(UserDTO user) {
userDAO.updateUser(ApiDTOBuilder.userDTOToUser(user));
}
How can I pass the userId and set the new parameters into the current user object?
Upvotes: 2
Views: 1020
Reputation: 786
First you need to fetch the User using DAO method. And then you need to set the values to the User entity. As you are using @Transactional, spring will take care of updating the values.
@Override
@Transactional
public void updateUser(Long userId,UserDTO userdto) {
User user= getUser(userId);
user.setFirstName(userdto.getFirstName());
user.setLastName(userdto.getLastName())
}
Also if you are not using Spring Boot, then you need to enable transaction management by using
@EnableTransactionManagement
Upvotes: 1