Disabling auto-commit in NamedParameterJdbcTemplate.batchUpdate

独自空忆成欢 提交于 2019-12-24 02:06:42

问题


I am doing a batch update into my DB table using NamedParameterJdbcTemplate.batchUpdate, but I would like to disable auto-commit and perform the commit manually.

I can set auto-commit mode off from the connection object, but not sure how to do the same using NamedParameterJdbcTemplate object.


回答1:


I have done my implementation using TransactionTemplate

It has an execute method and I do the business logic inside a callback in this function.

transTemplate.execute( new TransactionCallbackWithoutResult()
        {       
                @Override
                protected void doInTransactionWithoutResult( TransactionStatus status)
                {
                    status.setRollbackOnly();
                    //business logic
                }

        });



回答2:


I assume you are aware of the transactional management in Spring where by defining @Transactional and passing metadata of Propagation and Isolation you can elegantly manage transactions. If not take a look at the Spring documentation. In most cases that's all you need.

If you want to get transaction management at your own hands and fine-tune it (aka perform commit and rollbacks at will) you have to get the underlying TransactionManager directly.

Quoting from the Spring docs:

Using the PlatformTransactionManager

You can also use the org.springframework.transaction.PlatformTransactionManager directly to manage your transaction. Simply pass the implementation of the PlatformTransactionManager you are using to your bean through a bean reference. Then, using the TransactionDefinition and TransactionStatus objects you can initiate transactions, roll back, and commit.

DefaultTransactionDefinition def = new DefaultTransactionDefinition();
// explicitly setting the transaction name is something that can only be done programmatically
def.setName("SomeTxName");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

TransactionStatus status = txManager.getTransaction(def);
try {
  // execute your business logic here
}
catch (MyException ex) {
  txManager.rollback(status);
  throw ex;
}
txManager.commit(status);


来源:https://stackoverflow.com/questions/16842852/disabling-auto-commit-in-namedparameterjdbctemplate-batchupdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!