[英]Spring (Hibernate) updating issue
I have an issue in Spring (or Hibernate) with checking for data existence in DB till updating. 在Spring(或Hibernate)中,我有一个问题要检查数据库中是否存在数据,直到更新。 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";
}
}
EDIT : add elements for Hibernate persistence methods 编辑:为Hibernate持久性方法添加元素
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
. 如果您希望Hibernate自动地知道应该执行更新而不是插入操作,则必须在user
设置主键。 As you say the fields have been modified, I suppose user
fields come from a form input. 如您所说,字段已被修改,我想user
字段来自表单输入。 You have two ways to keep the id : 您可以通过两种方式保留ID:
@RequestMapping(/.../{id}) public String method(@PathVariable("id") user_id, ...)
) 将其放在路径变量中,将其放入控制器中,然后@RequestMapping(/.../{id}) public String method(@PathVariable("id") user_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. 但这可能还不够,您可能会遇到merge
vs update
vs saveOrUpdate
问题。 This other post from SO could give indications Hibernate : Downside of merge over update SO的另一篇文章可能暗示Hibernate:更新合并的缺点
比较args user.getId()与u.getId()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.