基于Spring Boot的MyBatis整合示例:构建简单的用户管理系统
以下是一个简化的Spring Boot和MyBatis整合的例子,展示了如何创建一个简单的用户管理系统:
// UserMapper.java
@Mapper
public interface UserMapper {
User selectUserById(int id);
int insertUser(User user);
int updateUser(User user);
int deleteUserById(int id);
}
// UserService.java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(int id) {
return userMapper.selectUserById(id);
}
public int createUser(User user) {
return userMapper.insertUser(user);
}
public int updateUser(User user) {
return userMapper.updateUser(user);
}
public int deleteUserById(int id) {
return userMapper.deleteUserById(id);
}
}
// UserController.java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUser(@PathVariable("id") int id) {
return userService.getUserById(id);
}
@PostMapping("/")
public int createUser(@RequestBody User user) {
return userService.createUser(user);
}
@PutMapping("/{id}")
public int updateUser(@PathVariable("id") int id, @RequestBody User user) {
user.setId(id);
return userService.updateUser(user);
}
@DeleteMapping("/{id}")
public int deleteUser(@PathVariable("id") int id) {
return userService.deleteUserById(id);
}
}
// User.java
public class User {
private int id;
private String name;
private String email;
// getters and setters
}
// application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/your_database
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
在这个例子中,我们定义了一个简单的User实体类,UserMapper接口用于定义数据库操作,UserService作为业务逻辑的处理,UserController负责处理Web请求。application.properties文件包含了数据库连接信息和MyBatis的映射文件位置。这个例子展示了如何在Spring Boot应用中整合MyBatis,并提供了一个简单的用户管理功能。
评论已关闭