数据库事务代码示例结合springcloud和mybatis
时间: 2023-10-21 11:01:33 浏览: 138
以下是一个简单的示例,展示如何在Spring Cloud和MyBatis中使用事务。
1. 创建一个MyBatis Mapper接口:
```java
public interface UserMapper {
@Insert("INSERT INTO users (name, age) VALUES (#{name}, #{age})")
void insertUser(@Param("name") String name, @Param("age") int age);
@Delete("DELETE FROM users WHERE id = #{id}")
void deleteUser(@Param("id") int id);
@Select("SELECT * FROM users WHERE id = #{id}")
User getUserById(@Param("id") int id);
@Update("UPDATE users SET name = #{name}, age = #{age} WHERE id = #{id}")
void updateUser(@Param("id") int id, @Param("name") String name, @Param("age") int age);
}
```
2. 创建一个Service类:
```java
@Service
@Transactional
public class UserService {
@Autowired
private UserMapper userMapper;
public void addUser(String name, int age) {
userMapper.insertUser(name, age);
}
public void deleteUser(int id) {
userMapper.deleteUser(id);
}
public User getUserById(int id) {
return userMapper.getUserById(id);
}
public void updateUser(int id, String name, int age) {
userMapper.updateUser(id, name, age);
}
}
```
3. 在配置类中配置事务管理器:
```java
@Configuration
@EnableTransactionManagement
public class AppConfig {
@Bean
public DataSource dataSource() {
// 配置数据源
return new DriverManagerDataSource();
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
return sessionFactory.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}
```
4. 在Controller中使用Service类:
```java
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/users")
public void addUser(@RequestParam String name, @RequestParam int age) {
userService.addUser(name, age);
}
@DeleteMapping("/users/{id}")
public void deleteUser(@PathVariable int id) {
userService.deleteUser(id);
}
@GetMapping("/users/{id}")
public User getUserById(@PathVariable int id) {
return userService.getUserById(id);
}
@PutMapping("/users/{id}")
public void updateUser(@PathVariable int id, @RequestParam String name, @RequestParam int age) {
userService.updateUser(id, name, age);
}
}
```
这样,当UserController中的任何一个方法被调用时,都会启动一个事务,如果方法执行成功,则提交事务,否则回滚事务。
阅读全文