MySQL数据库事务代码示例结合springcloudAlibaba和mybatis
时间: 2023-10-26 22:07:39 浏览: 84
下面是一个MySQL数据库事务的代码示例,结合了springcloudAlibaba和mybatis:
1. 配置数据源
在application.yml中配置数据源信息:
```yaml
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
```
2. 注入SqlSessionFactory
通过MybatisAutoConfiguration自动配置SqlSessionFactory,并注入到Spring容器中:
```java
@Configuration
@MapperScan(basePackages = "com.example.mapper")
public class MybatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
return sessionFactory.getObject();
}
}
```
3. 定义Mapper接口
创建Mapper接口,定义事务需要执行的数据库操作:
```java
@Mapper
public interface UserMapper {
@Insert("insert into user(name,age) values(#{name},#{age})")
void addUser(User user);
@Update("update user set age=#{age} where id=#{id}")
void updateUser(User user);
@Delete("delete from user where id=#{id}")
void deleteUser(Long id);
}
```
4. 定义Service层
在Service层中注入UserMapper,并使用@Transactional注解标注事务方法:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Transactional
public void addUser(User user) {
userMapper.addUser(user);
}
@Transactional
public void updateUser(User user) {
userMapper.updateUser(user);
}
@Transactional
public void deleteUser(Long id) {
userMapper.deleteUser(id);
}
}
```
5. 调用Service层方法
在Controller中调用UserService中的方法:
```java
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/addUser")
public void addUser(@RequestBody User user) {
userService.addUser(user);
}
@PutMapping("/updateUser")
public void updateUser(@RequestBody User user) {
userService.updateUser(user);
}
@DeleteMapping("/deleteUser/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
}
```
这样,当调用Controller中的方法时,将会执行UserService中的事务操作,保证数据的一致性和完整性。
阅读全文