springboot整合mybatis实现事物
创建数据库:
CREATE TABLE `usercount` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`username` varchar(20) DEFAULT NULL,
`money` int(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
pom.xml引入依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
application.yml文件配置:
#端口号配置
server:
port: 8800
#数据库连接四要素
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: root
password: 12345678
实体类:
@Data
public class UserCount {
private Integer id;
private String username;
private int money;
}
controller层:
@RestController
public class IndexController {
@Autowired
private UserService userService;
@RequestMapping("/index")
public String indexcontrller(String fromUser,String toUser,int money){
//index?fromUser=zhangsan&toUser=lisi&money=100
System.out.println("fromUser="+fromUser+",toUser="+toUser+",money="+money);
Map map = new HashMap();
map.put("fromUser",fromUser);
map.put("toUser",toUser);
map.put("money",money);
userService.modifyMoney(map);
//System.out.println(row);
return "xxx";
}
}
service层:
public interface UserService {
void modifyMoney(Map map);
}
service实现类:
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserCountDao userCountDao;
@Transactional(rollbackFor = Exception.class)//springboot自带事物,只需要加上事物注解,出现异常会自动回滚
@Override
public void modifyMoney(Map map) {
System.out.println("map="+map);
userCountDao.jianMoney(map.get("fromUser"),map.get("money"));
int i = 2/0;//
userCountDao.addMoney(map.get("toUser"),map.get("money"));
}
}
dao层:
@Mapper
public interface UserCountDao {
@Update("update usercount set money=money-#{money} where username = #{fromUser}")
void jianMoney(@Param("fromUser") Object fromUser,@Param("money") Object money);
@Update("update usercount set money=money+#{money} where username = #{toUser}")
void addMoney(@Param("toUser") Object toUser, @Param("money") Object money);
}
直接在此传参
访问方式:http://localhost:8800/index?fromUser=zhangsan&toUser=lisi&money=200