I am developing user module using jsp/servlet and hibernate. While updating user I was using same save method which is used while adding new user.
User service
public static User updateUserInstance(HttpServletRequest request) {
String id = request.getParameter("userId");
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String userName = request.getParameter("userName");
String gender = request.getParameter("gender");
String dob = request.getParameter("dob");
String email = request.getParameter("email");
String userType = request.getParameter("userType");
User user = getUser(Integer.parseInt(id));
System.out.println("User is : "+user);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setUserName(userName);
user.setGender(gender);
user.setDob(dob);
user.setEmail(email);
user.setUserType(userType);
return user;
}
UserDao
public boolean saveUser(User user) {
try{
SessionFactory factory = HibernateUtility.getSessionFactory();
Session session = factory.getCurrentSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
return true;
} catch(Exception e) {
System.out.println(e);
return false;
}
}
public boolean updateUser(User user) {
try{
SessionFactory factory = HibernateUtility.getSessionFactory();
Session session = factory.getCurrentSession();
session.beginTransaction();
session.update(user);
session.getTransaction().commit();
return true;
} catch(Exception e) {
System.out.println(e);
return false;
}
}
So my service is finding user based on Id and updating user values. After that I was using same save method of userDao and instead of updating that user It is creating new user. So I have created new method called updateUser.
I tried to find difference between save and update and found that save will insert into database if identifier doesn’t exist else it will throw an error. While in my case its not showing any error and creating new user. So I am not able to clearly identify how save and update internally works.
What are the differences between the different saving methods in Hibernate?
My question is quite different. I want to know same but its clear mentioned that in above question that "save Persists an entity. Will assign an identifier if one doesn't exist. If one does, it's essentially doing an update. Returns the generated ID of the entity." I asking same, My object has identifier still its creating new object instead of updating old object.