I have a scenario service layer is transactional, where i can only commit after done trandaction. i simplified it into like below.
begin transaction
for(loop){
getHibernateTemplate().save(object);
getHibernateTemplate().get(object_by_key); //cannot get object by object_by_key because "object" is not commit into database until entire for(loop) completed.
}
end transaction. commit();
i try to put getHibernateTemplate().flush(), after save() and able to see "insert" in show_sql. but the record is not showing inside database. how to force write to database after each save() rather than wait for commit like above ?
Obviously, you can. A hibernate session is more or less a database connection and a cache for database objects. And you can have multiple successive transactions in a single database connection. More, when you use a connection pool, the connection is not closed but is recycled.
1)The first difference between save and persist is there return type. Similar to save method, persist also INSERT records into the database, but return type of persist is void while return type of save is Serializable Object.
hibernate. Session class methods, save & saveOrUpdate is, save generates a new identifier and results in an INSERT query, whereas saveOrUpdate does an INSERT or an UPDATE. Save method stores an object into the database. That means it insert an entry if the identifier doesn't exist, else it will throw error.
getHibernateTemplate().flush() is the method to force hibernate to write to the database (send insert & update queries). This is done within a transaction so it is not visible to other transactions (querying from a SQL client) till the transaction is committed.
If the insert query is showing up in the log then it has been sent to the database. If you want to test that the record was inserted correctly - you can either do a getHibernateTemplate().clear() (which will remove all the cached data) and then do a getHibernateTemplate.get() (which will query from the dataSource). Or the other approach to test is to use the jdbcTemplate (with the same database) to query and check.
If the SQL client tool you are using allows you to specify the Isolation level - starting the SQL client session in isolation read_uncommited - would allow you to see the changes done even before the transaction is commited.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With