简体   繁体   中英

spring jpa @transaction doesn't rollback

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.

Adding @Repository in your UserDao can be a possible fix of that error.
Not sure but it can work.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM