If we do a update directly for one field it will set all other fields to their default values.
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
User user = new User();
user.password("xxxxx");
session.update(user);
tx.commit();
session.close();
above code sets all other fields to thier default values. so to avoid this we have to fetch the object from the table and then modify it and perform update operation.
We can either use session.load
or session.get
to fetch the object and update it.
code:
User u = session.load(User.class, userName);
u.setPassword(newPassword);
or
User u = session.get(User.class, userName);
u.setPassword(newPassword);
and then need to perform session.update(user)
full code:
SessionFactory factory = hibernateUtils.getSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
User user = session.load(User.class, username);
user.setPassword("xxxxxx");
session.update(user);
tx.commit();
session.close();
It’s good