开发者

want each call to save to commit

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.


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.


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:

  • Sessions and Transactions - https://www.hibernate.org/42.html

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:

  • Open Session in View - https://www.hibernate.org/43.html

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:

  • Non-Transactional Data Access and the Auto-Commit Mode - https://www.hibernate.org/403.html
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜