欢迎回到我们的MyBatis系列教程。在前几期中,我们详细探讨了MyBatis的进阶使用,包括多数据源配置、动态SQL生成器、MyBatis Generator的使用以及实现复杂查询的方法。这些知识点帮助我们在复杂的业务场景中更高效地使用MyBatis。本期内容中,我们将结合前面的所有知识点,进行一个完整的项目实战。通过实际项目的练习,大家将能够更好地巩固所学知识,并将其应用到实际开发中。
我们将开发一个简单的在线书店系统,该系统需要管理用户、书籍和订单信息。用户可以浏览书籍信息,下订单购买书籍,管理员可以管理书籍库存和订单状态。
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
password VARCHAR(100) NOT NULL,
email VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE books (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100) NOT NULL,
author VARCHAR(50),
price DECIMAL(10, 2),
stock INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE orders (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
book_id INT,
quantity INT,
total_price DECIMAL(10, 2),
status VARCHAR(20),
order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (book_id) REFERENCES books(id)
);
public class User {
private int id;
private String username;
private String password;
private String email;
private Timestamp createdAt;
// Getters and Setters
}
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User getUserById(int id);
@Insert("INSERT INTO users(username, password, email) VALUES(#{username}, #{password}, #{email})")
void insertUser(User user);
@Update("UPDATE users SET username=#{username}, password=#{password}, email=#{email} WHERE id=#{id}")
void updateUser(User user);
@Delete("DELETE FROM users WHERE id = #{id}")
void deleteUser(int id);
}
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(int id) {
return userMapper.getUserById(id);
}
public void insertUser(User user) {
userMapper.insertUser(user);
}
public void updateUser(User user) {
userMapper.updateUser(user);
}
public void deleteUser(int id) {
userMapper.deleteUser(id);
}
}
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUserById(@PathVariable int id) {
return userService.getUserById(id);
}
@PostMapping
public void insertUser(@RequestBody User user) {
userService.insertUser(user);
}
@PutMapping
public void updateUser(@RequestBody User user) {
userService.updateUser(user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable int id) {
userService.deleteUser(id);
}
}
public class Book {
private int id;
private String title;
private String author;
private BigDecimal price;
private int stock;
private Timestamp createdAt;
// Getters and Setters
}
public interface BookMapper {
@Select("SELECT * FROM books WHERE id = #{id}")
Book getBookById(int id);
@Insert("INSERT INTO books(title, author, price, stock) VALUES(#{title}, #{author}, #{price}, #{stock})")
void insertBook(Book book);
@Update("UPDATE books SET title=#{title}, author=#{author}, price=#{price}, stock=#{stock} WHERE id=#{id}")
void updateBook(Book book);
@Delete("DELETE FROM books WHERE id = #{id}")
void deleteBook(int id);
}
@Service
public class BookService {
@Autowired
private BookMapper bookMapper;
public Book getBookById(int id) {
return bookMapper.getBookById(id);
}
public void insertBook(Book book) {
bookMapper.insertBook(book);
}
public void updateBook(Book book) {
bookMapper.updateBook(book);
}
public void deleteBook(int id) {
bookMapper.deleteBook(id);
}
}
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@GetMapping("/{id}")
public Book getBookById(@PathVariable int id) {
return bookService.getBookById(id);
}
@PostMapping
public void insertBook(@RequestBody Book book) {
bookService.insertBook(book);
}
@PutMapping
public void updateBook(@RequestBody Book book) {
bookService.updateBook(book);
}
@DeleteMapping("/{id}")
public void deleteBook(@PathVariable int id) {
bookService.deleteBook(id);
}
}
public class Order {
private int id;
private int userId;
private int bookId;
private int quantity;
private BigDecimal totalPrice;
private String status;
private Timestamp orderDate;
// Getters and Setters
}
public interface OrderMapper {
@Select("SELECT * FROM orders WHERE id = #{id}")
Order getOrderById(int id);
@Insert("INSERT INTO orders(user_id, book_id, quantity, total_price, status) VALUES(#{userId}, #{bookId}, #{quantity}, #{totalPrice}, #{status})")
void insertOrder(Order order);
@Update("UPDATE orders SET user_id=#{userId}, book_id=#{bookId}, quantity=#{quantity}, total_price=#{totalPrice}, status=#{status} WHERE id=#{id}")
void updateOrder(Order order);
@Delete("DELETE FROM orders WHERE id = #{id}")
void deleteOrder(int id);
}
@Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
public Order getOrderById(int id) {
return orderMapper.getOrderById(id);
}
public void insertOrder(Order order) {
orderMapper.insertOrder(order);
}
public void updateOrder(Order order) {
orderMapper.updateOrder(order);
}
public void deleteOrder(int id) {
orderMapper.deleteOrder(id);
}
}
@RestController
@RequestMapping("/orders")
public class OrderController {
@Autowired
private OrderService orderService;
@GetMapping("/{id}")
public Order getOrderById(@PathVariable int id) {
return orderService.getOrderById(id);
}
@PostMapping
public void insertOrder(@RequestBody Order order) {
orderService.insertOrder(order);
}
@PutMapping
public void updateOrder(@RequestBody Order order) {
orderService.updateOrder(order);
}
@DeleteMapping("/{id}")
public void deleteOrder(@PathVariable int id) {
orderService.deleteOrder(id);
}
}
使用JUnit和Spring Boot的测试支持编写单元测试。
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTests {
@Autowired
private UserService userService;
@Test
public void testInsertUser() {
User user = new User();
user.setUsername("testuser");
user.setPassword("password");
user.setEmail("[email protected]");
userService.insertUser(user);
assertNotNull(userService.getUserById(user.getId()));
}
}
使用Postman或Swagger等工具进行API测试,确保各个接口功能正常。
使用Maven打包Spring Boot应用程序。
mvn clean package
将生成的jar
文件部署到服务器,并使用命令启动应用程序。
java -jar mybatis-demo-0.0.1-SNAPSHOT.jar
在下一期中,我们将进一步优化和扩展我们的在线书店系统。我们将探讨如何实现更多高级功能,如权限管理、搜索功能、数据导出等。通过这些高级功能的实现,大家将能够更全面地掌握MyBatis的使用,并提升系统的功能性和用户体验。
感谢大家的阅读,我们下期再见!