Hibernate save and receive using the same session with the same transaction

I have a transactional script service level where I can make transactions only after trandaction has been completed. I simplified it as shown 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 am trying to put getHibernateTemplate (). flush () after save () and will be able to see "insert" in show_sql. but the record does not appear inside the database. How to force a record to the database after each save (), and not wait for a commit, as described above?

+7
source share
4 answers

getHibernateTemplate (). flush () is a forced sleep mode method for writing to the database (sending insert and update requests). This is done in a transaction, so it is not visible to other transactions (queries from the SQL client) until the transaction is completed.

If the insert request appears in the log, it is sent to the database. If you want to check the correct installation of the record, you can do getHibernateTemplate (). Clear () (which will delete all cached data), and then do getHibernateTemplate.get () (which will request data from the data source), Or another testing approach is to use jdbcTemplate (with the same database) to query and validate.

If the SQL client tool used allows you to specify the level of isolation — starting an SQL client session in read_uncommited isolation — allows you to see the changes made before the transaction was made.

+5
source

Does getHibernateTemplate () get the same template every time? Or, if not a template based on a shared session. You might be better off not storing the template in a local variable and reusing it, rather than calling getHibernateTemplate () every time.

 begin transaction template = getHibernateTemplate(); for(loop){ template.save(object); template.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 think your problem may be due to the fact that you are using a different session to save and receive calls. If they are made in one session, you should see the behavior you want.

0
source

As I know, you cannot do this. This does not work. Unable to retrieve stored object in the same transaction. I think this is because the session is a first-level cache, and Hibernate can only get a new object when another transaction that creates this object is completed.

0
source

Why do you need an object by key? You already have an object! If you really need an object key (to print it?), You can use a new transaction for each save operation by putting transaction begin and commit in a loop.

0
source

All Articles