【Spring Boot学习之四】Spring Boot事务管理

环境
  eclipse 4.7
  jdk 1.8
  Spring Boot 1.5.2

一、springboot整合事务
事务分类:编程事务、声明事务(XML、注解),推荐使用注解方式,springboot默认集成事物,只主要在方法上加上@Transactional即可
1、controller

package com.wjy.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wjy.test1.service.UserServiceTest1;


@RestController
public class UserController {

    @Autowired
    public UserServiceTest1 userServiceTest1;
    
    @RequestMapping("/insertTest1ByService")
    public String insertTest1ByService(String name,Integer age) {
        userServiceTest1.insertuser1(name, age);
        return "success";
    }
    
    
}

2、service

/**
 * 
 */
package com.wjy.test1.service;

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

import com.wjy.test1.dao.UserMapperTest1;

/**
 * @Desc
 * @author wangjy15
 */
@Service
public class UserServiceTest1 {
    
    @Autowired
    private UserMapperTest1 userMapperTest1;
    
    /**
     * @Description: 如果没有事务控制 那么报错之后  插入到库里的数据不会回滚  加上 注解@Transactional  就可以回滚
     */
    @Transactional
    public String insertuser1(String name,Integer age) {
        userMapperTest1.insert(name, age);
        int i =1/0;
        return "success";
    }

}

3、mapper

/**
 * 
 */
package com.wjy.test1.dao;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import com.wjy.entity.User;

/**
 * @Desc
 * @author wangjy15
 */
public interface UserMapperTest1 {
    
    @Select("SELECT * FROM users WHERE NAME = #{name}")
    User findByName(@Param("name") String name);

    @Insert("insert into users (name,age) values(#{name},#{age})")
    int insert(@Param("name") String name,@Param("age") Integer age);
}

4、APP

package com.wjy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class APP {

    public static void main(String[] args) {
        SpringApplication.run(APP.class, args);
    }

}

5、测试验证

http://localhost:8080/insertTest1ByService?name=wangsan0010&age=1000

二、SpringBoot分布式事务管理
传统项目:jta+automatic

猜你喜欢

转载自www.cnblogs.com/cac2020/p/11230967.html