简体   繁体   English

spring jpa @transaction不回滚

[英]spring jpa @transaction doesn't rollback

My project encountered the problem that Spring JPA transactions would not roll back. 我的项目遇到了Spring JPA事务不会回滚的问题。 The project framework is spring MVC + Spring + spring data JPA + oracle. 该项目框架是spring MVC + spring + spring data JPA + oracle。 I searched a lot of information on the Internet, but still could not solve my problem. 我在Internet上搜索了很多信息,但仍然无法解决我的问题。

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. 我尝试了很多方法,例如将方法设置为public或在@Transactional添加rollbackFor = Exception.class ,但仍然无法解决。

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. 我的@Transactional方法加载了我的实现类Service,该类写入容易出错的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. 添加@Repository在你的UserDAO可以是错误的可能修复。
Not sure but it can work. 不确定,但是它可以工作。

Oh, I solved it because I omitted in applicationContext.xml. 哦,我解决了它,因为我在applicationContext.xml中省略了。 I only wrote in spring-mvc.xml. 我只写了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. 直到我看到这篇文章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 如果您在springboot项目上下文中,则必须在配置类中添加@EnableTransactionManagement

if it's a non springboot project, add in your xml configuration file (where is declared your component-scan) the annotation-driven tag 如果它是非springboot项目,则在xml配置文件(声明为组件扫描)中添加注释驱动的标签

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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