executeUpdate in createQuery does not update my database

336 Views Asked by At
public void updateUserState(User user) {
        Session sess=getSession();
        sess.setFlushMode(FlushMode.MANUAL);
        String queryStr = "update User usr set usr.logCount = :logCount , usr.isLocked = :isLocked , usr.lastLogin = :lastLogin where usr.userId=:userId";
        Query query=null;
        query = sess.createNativeQuery(queryStr);
        query.setParameter("logCount", user.getLogCount());
        query.setParameter("isLocked", user.getIsLocked());
        query.setParameter("lastLogin", user.getLastLogin());
        query.setParameter("userId", user.getUserId());
        query.executeUpdate();
}

This is my code. This does not update mu user table in database , neither does this throw any error. It reflects the correct value till set parameter but after executeUpdate, I cannot see any update in my table. It would be really nice if anyone of you can tell me, where am I going wrong. Thanks in advance!

1

There are 1 best solutions below

0
On

According to the hibernate documentation flush type MANUAL assume:

The Session flushing is delegated to the application, which must call Session.flush() explicitly in order to apply the persistence context changes.

So, you should explicitly call Session.flush() in the end of your method.

Also your updateUserState method should be ran inside a transaction:

Session sess = getSession();
sess.setFlushMode(FlushMode.MANUAL);
Transaction txn = sess.beginTransaction();
// ...
query.executeUpdate();

sess.flush();
txn.commit();
session.close();