Spring Transaction in Java main method

Dec 09 2011 Published by under Java

In standalone java project (main method) if you insert / update database it will not work. It is because you need to add the transaction management. You need to do programmatic transaction management. Here is the code you need to add in your main method.


PlatformTransactionManager transactionManager = (PlatformTransactionManager) context.getBean("transactionManager");
DefaultTransactionDefinition transDef = new DefaultTransactionDefinition();
TransactionStatus ts = transactionManager.getTransaction(transDef);
<<< YOUR CODE GOES HERE >>>

For e.g.,
<<< context.getBean(CustomerService.class).addCustomer(customer); >>>
transactionManager.commit(ts);

UPDATE
Adding @Transactional annotation to you Dao or Service class is another way to solve this.

No responses yet

Leave a Reply