i read that upon session.flush()
The data will be synchronized (but not committed) when session.flush() is called
what is synchronized with what.. whether it is DB state that will come to memory by querying or memory state will be c开发者_如何学运维opied to Db ?
clarify this plz..
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.
"Flushing is the process of synchronizing the underlying persistent
store with persistable state held in memory."
By default the flush mode is set to AUTO and in this case session is flushed before query execution in order to ensure that queries never return stale state.
Flushing synchronizes the underlying persistent store with persistable state held in memory but not vice-versa. In other words, "in memory state is copied to the database" in the running transaction, to reuse your words. Note that flushing doesn't mean the data can't be rolled back.
精彩评论