简体   繁体   中英

When to call flush() and commit() in Hibernate?

I have the following case:

        openSession()

        tx = session.beginTransaction();

    try
    {
        ...
        session.saveOrUpdate(obj_1);
        ...
        session.saveOrUpdate(obj_2);
        ...
        session.saveOrUpdate(obj_3);

        session.flush();
        tx.commit();
    }
    catch()
    {
       tx.rollback()
    }
    finally
    {
        session.close();
    }

The first call of saveOrUpdate(obj_1) will failed due to Duplicate entry error. But this error would not actually happen until the database is accessed at the end of the session.flush() .

Is there a way to make this kind of error happens early and give me more chance to correctly handle it?

I also don't want to cut the transaction too small because it is hard to rollback.

My Hibernate entities are reversed from an existing database schema.

I have disabled the cache in my configuration file:

<property name="hibernate.cache.use_second_level_cache">false</property>
<property name="hibernate.cache.use_query_cache">false</property>   

EDIT:

My question is how can I get the error as early as possible if any. The error itself doesn't matter to me.

Right now the error happens at the end, but it actually happened at the first access.

You can execute session.flush() after each session.saveOrUpdate to force hibernate to execute the update or insert on your database. Without the flush command the actual database operations are deferred and will only be processed immediately before ending the transaction.

This way you don't have to change the size of your transaction.

You can execute Surendran after each session.saveOrUpdate to force hibernate to execute the update or insert on your database. Without the flush command the actual database operations are deferred and will only be processed immediately before ending the transaction.

This way you don't have to change the size of your transaction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM