tags:

views:

70

answers:

2

How can I have each call to save commit to the database?

I don't want to, at each interation of a loop that I am in, to call commit and then restart the transaction.

for my application, just having a commit at each session.save is fine.

+2  A: 

So code it that way:

// connection is passed into the method.
try
{
    connection.setAutoCommit(false);
    PreparedStatement ps = connection.prepareStatement(...);
    // bind variables
    for (Collection stuff : stuffList)
    {  
        // save repeatedly 
    }
    connection.commit();
}
catch (SQLException e)
{
   DatabaseUtils.rollback(connection);
}
finally
{
    DatbaseUtils.close(statement);
    DatabaseUtils.close(connection);
}

Transactions are a cross-cutting concern. Best not to have transactional logic like this inside your persistence tier, especially if more than one data access object has to participate in a single unit of work.

duffymo
+1  A: 

EDIT: use a hibernate transaction:

Session s = factory.getCurrentSession();
try {
  s.beginTransaction();
  Thing thing = new Thing();
  s.save(thing);
  s.getTransaction().commit();
} catch (RuntimeException e) {
  s.getTransaction().rollback();
  throw e;
}

Transaction handling with hibernate is detailed here:

In a servlet environment, hibernate recommends implementing a filter that starts a transaction when the request begins and ends it when the request is done. Sample code here:

If using JTA or EJB there are methods to work with the existing transaction context as described in the guide.

You could alternatively turn autoCommit mode on (which is disabled by default). Each statement would effectively be executed in a separate transaction. This is controlled by the "hibernate.connection.autocommit" option. More details here:

jspcal
No indication that he's using Hibernate at all. It might be more complex than he can handle.
duffymo
its hibernate, yeah that is why I tagged it as such :)
mrblah
Be careful with that catch-clause there, you will loose the execption in case rollback() fails also. A workaround would be log the exception before attempting to rollback.
Willi
if rollback fails, it will throw an exception which gets propagated up the chain. you could use a chained exception if you need more detail
jspcal