Consider the below code that loads an entity from the database and deletes it.
Note: This property does not work when the assigned generator is used. Same is the case when using composite identifiers.
public static void rollBackDelete() { Session session = sessionFactory.openSession(); Entity entity = new Entity(); entity.setData("Temp Object"); Transaction transaction = session.beginTransaction(); session.save(entity); System.out.println("The id is " + entity.getId()); // Object will be saved to the db transaction.commit(); transaction = session.beginTransaction(); session.delete(entity); transaction.commit(); session.close(); System.out.println("The id is " + entity.getId()); }The two println() calls to the console outputs the following line:
The id is 10 The id is 10It is possible to tell hibernate to rollback the value of the identifier on entity delete. i.e. when Hibernate executes the delete call successfully, it will set the value of id to null. This is achieved by adding the following property in the hibernate configuration file:
<property name="hibernate.use_identifier_rollback">true</property>On executing the same code as before the output is now as below:
359 [main] DEBUG org.hibernate.cfg.Configuration - hibernate.use_identifier_ro llback=true ... 1546 [main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: enabled ... The id is 10 ... The id is nullThe object is now a clean transient instance with no value representing the database identifier in it.
Note: This property does not work when the assigned generator is used. Same is the case when using composite identifiers.
No comments:
Post a Comment