Reputation: 335
I have an issue in Spring (or Hibernate) with checking for data existence in DB till updating. I want to update user’s profile and I can change Name, Password and Email fields. Name and Password hasn’t to be unique but Email has to. I show the form with fields filled by user’s old data, when I enter new data not changing Email it, of course, shows that it is already exists. If delete this check I’ll have two same emails in base. How can I set same data for certain user?
My method for update with checking email.
public void updateUser(User user) throws NotUniqueEmailException {
if (user == null) {
throw new NullPointerException();
}
if (user.getUserId() < 1) {
throw new IllegalArgumentException();
}
if (user.getEmail() == null || user.getEmail().intern().equals("")) {
throw new IllegalArgumentException();
}
if (getUserByEmail(user.getEmail()).getEmail() != null) {
throw new NotUniqueEmailException("The email of user not unique! " + user.getEmail());
}
currentSession().update(user);
// currentSession().saveOrUpdate(user);
}
And I’ve one more method for checking for existence.
public boolean isEmailExists(User user) {
Session session = HibernateUtil.openSession();
boolean result = true;
Query query = session.createQuery("SELECT u FROM User u WHERE u.email=?");
query.setString(0, user.getEmail());
User u = (User) query.uniqueResult();
if (u == null) {
result = false;
}
return result;
}
Update controller
@RequestMapping(value = "/edit/{userId}", method = RequestMethod.GET)
public String updateView(@PathVariable("userId")Integer userId,
UserForm userForm,
HttpSession session,
ModelMap model){
User user=userService.getUserById(userId);
userForm.setUser(user);
model.addAttribute("userForm",userForm);
return"profileupdate";
}
@RequestMapping(value = "/edit.do/{userId}", method = RequestMethod.POST)
public String updateUserProcess(@ModelAttribute(value = "userForm")
UserForm userForm,
@PathVariable("userId")Integer userId,
BindingResult result,Model model,
HttpSession session,
HttpServletRequest request){
User user=userService.getUserById(userId);
session.getAttribute("userForm");
model.addAttribute("userForm",userForm);
updateValidator.validate(userForm,result);
if(result.hasErrors()){
logger.error("Validation error");
return"profileupdate";
}
return updatingUser(userForm,user,model,request);
}
private void fillForm(UserForm userForm,User user){
userForm.setUserId(user.getUserId());
userForm.setLogin(user.getLogin());
userForm.setRegDate(user.getRegDate());
userForm.setComputers(userService.getAllUsersComputers(user.getLogin()));
userForm.setRole(roleService.findByName(user.getRole().getRoleName()));
}
private String updatingUser(UserForm userForm,User user,Model model,HttpServletRequest request){
fillForm(userForm,user);
user=userForm.getUser();
try{
userService.updateUser(user);
logger.info("User updated!");
request.getSession().setAttribute("user",user);
return"newprofile";
}catch(NotUniqueEmailException e){
logger.error("Can't update user - not unique email!!",e);
model.addAttribute("errorMsg","Email is already in use!");
return"profileupdate";
}
}
Upvotes: 1
Views: 195
Reputation: 149175
EDIT : add elements for Hibernate persistence methods
If you want Hibernate to automagically know that it should do an an update and not an insert, the primary key has to be set in user
. As you say the fields have been modified, I suppose user
fields come from a form input. You have two ways to keep the id :
@RequestMapping(/.../{id}) public String method(@PathVariable("id") user_id, ...)
)But it may not be enough and you could have a merge
vs update
vs saveOrUpdate
problem. This other post from SO could give indications Hibernate : Downside of merge over update
Upvotes: 2