MayoMan
MayoMan

Reputation: 4917

Hibernate not updating database after flush()

I created my DB manually and then used Hibernate tools to generate my Pojo, DAOs. When I create an object and persist it to the database it appears to work fine

        DefinitionT def = new DefinitionT();
        def.setSelected(false);
        def.setValue(sqlEncode(definition));
        def.setWordId(wordT.getId());
        definitionTDao.persist(def);

This is my persist() method

public void persist(Object o)
{
    try
    {
        hSession.persist(o);
        hSession.flush();
    }
    catch (Exception e)
    {
        hTransaction.rollback();
        log.error(e.getMessage());
    }
}

When my thread completes the database is updated with the new object. However, I noticed that if I stop the program directly after I call persist() the database will not have been updated. In fact, no matter how many operations I perform nothing seems to get updated in the DB until the thread completes. I thought flush() pushed all updates in the hibernate cache into the database? What am I missing? I think this is the same issue as Hibernate flush doesn't update database but I don't have any for loop going on.

Upvotes: 3

Views: 11611

Answers (2)

Elbek
Elbek

Reputation: 3484

What about if you commit transaction explicitly:

Transaction hTransaction = null;
try {
hTransaction = hSession.beginTransaction();

hSession.persist(o);


hTransaction.commit();
hSession.flush();

}
catch (Exception e)
{
    hTransaction.rollback();
    log.error(e.getMessage());
}

Actually As I know when you flush the session, any transaction that opened with this session should be committed, but check with this, Make sure you are creating transaction with the session that you are flushing.

Just checked for automatically flush when you you commit, mode should be:

hSession.setFlushMode(FlushMode.COMMIT)

check from here

Upvotes: 2

Johanna
Johanna

Reputation: 5293

Flush means the Hibernate session eventually orders the SQL statements and then sends them to the database. The database then executes them (in the rollback segments) but does not make the modifications persistent neither makes them available to other users.

A commit finally let the database persistently store the modifications. (The exceptions are if the database is in autocommit mode - which I would not recommend as the correctness of transactions can't be guaranteed then, and autocommit is not available for all databases, or if the flush mode is set to commit - also not necessary; that looses flexibility.)

A commit implicitely calls a flush(), but flush does not call commit().

The solution for you: Do an extra commit at the end of your program.

(By the way, often a flush is done after every transaction, but a commit is done after many transactions only for better performance.)

Upvotes: 8

Related Questions