首先,需要在项目的pom.xml文件中添加MyBatis和数据库驱动的依赖。使用mybatis-spring-boot-starter来实现快速集成,并加入MySQL驱动程序mysql-connector-java来实现与数据库的连接。
<dependencies> <!-- MyBatis Spring Boot Starter 依赖 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <!-- MySQL驱动程序 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies>
创建数据库映射实体类
接下来,需要创建一个与数据库表对应的实体类。例如,如果有一个user表,可以创建一个User实体类:
public class User { private Long id; private String name; private String email; // getters and setters }
创建Mapper层接口
在MyBatis中,Mapper层接口用于定义数据库操作的方法。以下是一个简单的UserMapper接口示例:
@Mapper public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User findUserById(Long id); @Insert("INSERT INTO user(name, email) VALUES(#{name}, #{email})") int insertUser(User user); @Update("UPDATE user SET name = #{name}, email = #{email} WHERE id = #{id}") int updateUser(User user); @Delete("DELETE FROM user WHERE id = #{id}") int deleteUser(Long id); }
创建Service层
Service层用于封装业务逻辑,并调用Mapper层接口中的方法。以下是一个简单的UserService接口和实现:
@Service public interface UserService { User getUserById(Long id); void createUser(User user); void updateUser(User user); void deleteUser(Long id); } @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User getUserById(Long id) { return userMapper.findUserById(id); } @Override public void createUser(User user) { userMapper.insertUser(user); } @Override public void updateUser(User user) { userMapper.updateUser(user); } @Override public void deleteUser(Long id) { userMapper.deleteUser(id); } }
创建Controller层
最后,创建一个UserController来处理HTTP请求,并调用Service层的方法:
@RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { return userService.getUserById(id); } @PostMapping("") public ResponseEntity<User> createUser(@RequestBody User user) { userService.createUser(user); return ResponseEntity.ok(user); } @PutMapping("/{id}") public User updateUser(@PathVariable Long id, @RequestBody User user) { user.setId(id); userService.updateUser(user); return user; } @DeleteMapping("/{id}") public void deleteUser(@PathVariable Long id) { userService.deleteUser(id); } }