Home > Back-end > Spring @ Transactional throws an exception, when will the rollback?
Spring @ Transactional throws an exception, when will the rollback?
Time:09-22
Today try to transaction rollback and encounter a problem: In my controller try a method, this method performs a statements with @ Transactional annotation, and an exception is thrown, the controller in the catch this exception, from the console output into the content of the , I feel should be inserted into the statement is rolled back, content to be deleted, but the result is: the database is rolled back, and did the output content is inserted, Want to ask a great god, and what is this principle? Controller:
@ RequestMapping ("/regist ") Public ModelAndView regist (it request, User User) throws the Exception { If (checkParams (new String [] {user. GetUsername (), the user, getPassword ()})) { //TODO @ Transaction check if the account has already exist Try { UserService. SaveUser (user); } the catch (Exception e) { //TODO Auto - generated the catch block, System. The out. Println (" regist "+ um participant etMessage ()); Request. SetAttribute (" go ", um participant etMessage ()); } Request. SetAttribute (" username ", the user. The getUsername ()); Request. SetAttribute (" password ", user. GetPassword ()); System.out.println(user); Return new ModelAndView (" succ "); } Return new ModelAndView (" regist "); }
Service:
@ Transactional (rollbackFor=Exception class) Public void saveUser User (User) throws the Exception { If (the user!=null & amp; & User. GetId ()!=null) { UserDao. UpdateUser (user); } else { //TODO find if there is a repetition, can also use SQL Try { List AllUser=userDao. GetUser (); UserDao. InsertUser (user); For (User _user: allUser) { If (_user. GetUsername () equals (user. The getUsername ())) Throw new Exception (" The account is exist!" ); } } the catch (Exception e) { Throw e; } } }
The console output: The User [userid=1, the username=1, the password=1] RegistThe account is exist! The User [userid=2, the username=1, the password=2] Database:
CodePudding user response:
The practice of the spring configuration will be thrown when RuntimeException rolled back, when you many times to the database operation, only successful when all will pass, otherwise will all rollback, personal understanding,
CodePudding user response:
Principle I don't know if
CodePudding user response:
Want to know the principle is to look at the underlying code , I am also a small white
CodePudding user response:
@ love1390700626 just don't know why the rollback is successful, insert data exists, should be deleted: