Reputation: 35
My project encountered the problem that Spring JPA transactions would not roll back. The project framework is spring MVC + Spring + spring data JPA + oracle. I searched a lot of information on the Internet, but still could not solve my problem.
I've tried many ways, such as setting the method to public or adding rollbackFor = Exception.class
in @Transactional
, but it still can't be solved.
Here's my code
Controller
@RequestMapping(value = {"addUser"}, method = RequestMethod.GET)
@ResponseBody
public Boolean insertUser() throws Exception{
User user = new User();
user.setId(10);
userServiceI.addUser(user);
return true;
}
Service
Service Interface
public interface UserServiceI {
void addUser(User user);
}
Service Implementation class
@Service
public class UserService implements UserServiceI {
@Autowired
public UserDao userDao;
@Autowired
PersonService personService;
@Override
@Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class)
public void addUser(User user){
User user1 = userDao.saveAndFlush(user);
System.out.println(1/0);
}
}
Dao
public interface UserDao extends JpaRepository<User,Integer> {
}
My @Transactional
method loads my implementation class Service, which writes an error-prone 1/0. I expect the transaction to roll back after the error, but it doesn't.
Upvotes: 0
Views: 1731
Reputation: 35
Oh, I solved it because I omitted in applicationContext.xml. I only wrote in spring-mvc.xml. I always thought that I only need to write this in one of them. Until I saw this article labreeze.iteye.com/blog/2359957. I am too happy and negligent.
Upvotes: 0
Reputation: 86
Adding @Repository
in your UserDao can be a possible fix of that error.
Not sure but it can work.
Upvotes: 2
Reputation: 397
if you are in a springboot project context you have to add @EnableTransactionManagement in your configuration class
if it's a non springboot project, add in your xml configuration file (where is declared your component-scan) the annotation-driven tag
Upvotes: -1