SpringBoot事务管理

时间:2021-01-03 12:57:49

1、在UserMapper接口中添加更新和删除方法

package com.cppdy.mapper;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update; import com.cppdy.entity.User; @Mapper
public interface UserMapper { @Select("select * from user where id=#{id}")
User getUserById(@Param("id") int id); @Insert("insert into user values(NULL,#{name})")
User insertUser(@Param("name") String name); @Update("update user set username=#{name} where id=#{id}")
User update(@Param("id") int id,@Param("name") String name); @Delete("delete from user where id=#{id}")
User delete(@Param("id") int id);
}

2、创建UserService接口

package com.cppdy.service;

public interface UserService {

    //执行事务
public void tranfor(); }

3、创建UserServiceImpl实现类(@Transactional开启事务管理)

package com.cppdy.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.cppdy.mapper.UserMapper;
import com.cppdy.service.UserService; @Service
public class UserServiceImpl implements UserService { @Autowired
private UserMapper userMapper; // 开启事务管理
@Transactional
public void tranfor() {
// 更新一条数据
userMapper.update(2, "cppdy123");
// 抛出一个异常
int a = 2 / 0;
// 删除一条数据
userMapper.delete(2);
} }

4、在HelloWordController类中创建测试方法

@RequestMapping("tranfor")
public void tranfor() { userService.tranfor();
}