Search code examples
javahibernatehsqldb

How to make HSQL not auto update entity when change entity's field


I have an entity and whenever I edit its field, HSQL immediately updates the entity.

The code below

System.out.println(userService.findById(user.getId()).getPassword());

user.setPassword("password");

System.out.println(userService.findById(user.getId()).getPassword());

userService.update(user);

System.out.println(userService.findById(user.getId()).getPassword());

prints out in the console

qwerty
password
password

which means that even before I use update(), the entity is already updated.

How can I stop it? So that entity can be only updated invoking the method, but not when you change its field.

Hibernate config:

jdbc.driverClassName=org.hsqldb.jdbc.JDBCDriver
jdbc.url=jdbc:hsqldb:mem:myDb
jdbc.username=sa
jdbc.password=sa
hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.hbm2ddl.auto=create

Solution

  • I'm assuming you have a transaction open around the following code:

    System.out.println(userService.findById(user.getId()).getPassword());
    user.setPassword("password");
    System.out.println(userService.findById(user.getId()).getPassword());
    userService.update(user);
    System.out.println(userService.findById(user.getId()).getPassword());
    

    What happens is Hibernate fetches the entity and since it's still within a transaction the entity is a hibernate managed entity so ANY changes to the entity (e.g. user.setPassword(...) will result in those changes being flushed to the DB.

    If you instead only make the userService transactional (i.e. remove the transaction from surrounding the example code and annotate the userService as @Transactional (assuming you're using Spring)) then when you do the user.setPassword(...) it will be OUTSIDE of a transaction and the changes won't persist.

    Alternatively you can force the entity to detach (so that it's no longer managed) by calling the EntityManager::detach method.

    For additional context read section 3.5 in the following link: https://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/objectstate.html