(十四)SpringBoot之事務處理

1、簡介

ssh ssm都有事務管理service層經過applicationContext.xml配置,全部service方法都加上事務操做;java

用來保證一致性,即service方法裏的多個dao操做,要麼同時成功,要麼同時失敗;web

springboot下的話,在service方法上加上@Transactional便可spring

 

2、案例

   2.1  controller

package com.shyroke.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shyroke.dao.UserMapper;
import com.shyroke.entity.UserBean;
import com.shyroke.service.UserService;

@Controller
@RequestMapping(value = "/")
public class IndexController {

    @Autowired
    private UserService userService;
    
    @ResponseBody
    @RequestMapping(value="/save")
    public String list() {
    
        UserBean user1=new UserBean();
        user1.setUserName("user1");
        user1.setPassWord("123");
    
        userService.save(user1);
        
        return "index";
        
        
    }
}

 

  • service

package com.shyroke.service;

import com.shyroke.entity.UserBean;

public interface UserService {

    void save(UserBean user1);

}

 

  • service實現類

  在下面的代碼中,咱們對save方法加上了@Transactional註解,表示使用事務,當有異常拋出時,就會自動回滾。數據庫

package com.shyroke.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shyroke.dao.UserMapper;
import com.shyroke.entity.UserBean;
import com.shyroke.service.UserService;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;
    
    @Override
    @Transactional public void save(UserBean user1) {
    
        userMapper.save(user1);
        
        boolean flag = true;
        if (flag) {
        throw new RuntimeException();
        }
        
    }

}

 

  • mapper

package com.shyroke.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.shyroke.entity.UserBean;

public interface UserMapper extends JpaRepository<UserBean, Integer>{

}

 

  •   結果:

數據庫沒有數據,說明已經被回滾了。springboot

相關文章
相關標籤/搜索