简体   繁体   中英

Get the generated Id from the last insert in the Controller, Spring

This is my controller that saves form data in the database:

@RequestMapping(value = "/user/newUser", method = RequestMethod.POST)
public ModelAndView createNewSurvey(@Valid User user, BindingResult bindingResult) {
    ModelAndView modelAndView = new ModelAndView();
    userService.saveUser(user);
    modelAndView.addObject("successMessage", "Added user!");
    modelAndView.addObject("user", new User());
    modelAndView.setViewName("user/newUser");
    return modelAndView;
}

After calling saveUser, how do I get the generated ID for that user in this controller, so that I can use it to call another function ? Thank you

Edit :

UserService implementation :

@Service("userService")
public class UserServiceImpl implements UserService {

@Autowired
private UserRepository userRepository;
@Override
public void saveUser(User user) {
    userRepository.save(user);
}

try the following the let me know if it worked for you

@Override
public User saveUser(User user) {
    return userRepository.save(user);
}

change also the interface method to return the User in the UserService Interface

public User saveUser(User user);

then in the controller just call the getId() from the returned UserObject

User newUser = userService.saveUser(user);
newUser.getId();

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