Calling session.flush()
will cause SQL statements to be generated for all of the changes you have made, and those SQL statements to be executed on the database, within the sessios transaction scope.
Car car = (Car) session.get(Car.class, 1);
car.setModel("Mustang");
session.flush();
The last line will cause an UPDATE
statement on the database. However, depending on how you handle transactions in your applications, this change might not be visible to other users before you commit the transaction held by the section.
While flushing is not really a bi-directional operation, it can be used to ensure that an auto generated identifier is assigned to a new entity object. If the Car
class is mapped to a database table with an auto incrementing identifier, you can use flush to ensure that this identifier is available on the domain object in your application code:
Car car = new Car();
car.setModel("Torino");
session.save(car);
System.out.println(car.getId()); // prints 0
session.flush();
System.out.println(car.getId()); // prints something larger than 0
Say you want to send an email with a link to the newly created car (ok, a user account would have made more sense), but if the mail cannot be sent, you wish to rollback your transaction. Flushing the session allows you to do this.