Today, I encountered a strange thing. I configured transactions in the Spring configuration file and performed transactions on all methods at the Service layer. However, when I tested one of the methods, it is found that it is not a transaction, and the first operation in it is completed, but the second operation fails. The reason is found. It turns out that the try and catch statement blocks are used inside this method, so that exceptions are caught internally. In Spring, transaction rollback is triggered by exceptions. That is to say, the servcie layer method cannot capture exceptions. It should be thrown up or not written (or thrown out of exceptions), so that Spring transactions will take effect.
The Spring configuration file is as follows:
<Bean id = "txManager" class = "org. springframework. orm. hibernate3.HibernateTransactionManager">
<Property name = "sessionFactory" ref = "mySessionFactory"/>
</Bean>
<Tx: advice id = "txAdvice" transaction-manager = "txManager">
<Tx: attributes> www.2cto.com
<Tx: method name = "*" propagation = "REQUIRED"/>
</Tx: attributes>
</Tx: advice>
<Aop: config>
<Aop: pointcut id = "productServiceMethods" expression = "execution (public * com. sq. hps. modules. *. service... * (..)"/>
<Aop: advisor advice-ref = "txAdvice" pointcut-ref = "productServiceMethods"/>
</Aop: config>
You can use Junit for testing:
Public class UserTest {
@ Test
Public void testAddBackRole (){
BackRole backRole = new BackRole ();
BackRole. setName ("test11 ");
BackRole. setDescription ("test ");
BackRole. setParkingIds ("");
String privilegeStr = "";
ApplicationContext ctx = new ClassPathXmlApplicationContext ("applicationContext. xml ");
UserService userService = (UserService) ctx. getBean ("userService ");
System. out. println (userService );
UserService. addBackRole (backRole, privilegeStr );
}
}