Spring Boot + MySQL 实现用户购买及商家订单查看功能
Spring Boot + MySQL 实现用户购买及商家订单查看功能
本教程将引导您使用 Spring Boot 和 MySQL 数据库构建一个简单的电商功能模块,实现用户购买物品和商家查看订单信息。
1. 数据库设计
首先,创建两个数据库表:'user' 表存储用户信息,'item' 表存储物品信息。sqlCREATE TABLE user ( id int(11) NOT NULL AUTO_INCREMENT, username varchar(50) NOT NULL, password varchar(50) NOT NULL, PRIMARY KEY (id)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
CREATE TABLE item ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(50) NOT NULL, price decimal(10,2) NOT NULL, quantity int(11) NOT NULL, PRIMARY KEY (id)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
为了记录订单信息,还需要创建一个 'order' 表:sqlCREATE TABLE order ( id int(11) NOT NULL AUTO_INCREMENT, user_id int(11) NOT NULL, item_id int(11) NOT NULL, quantity int(11) NOT NULL, total_price decimal(10,2) NOT NULL, create_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), FOREIGN KEY (user_id) REFERENCES user (id), FOREIGN KEY (item_id) REFERENCES item (id)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
2. 创建实体类
根据数据库表结构,创建对应的 Java 实体类:User、Item 和 Order。javapublic class User { private Long id; private String username; private String password; // getter and setter}
public class Item { private Long id; private String name; private BigDecimal price; private Integer quantity; // getter and setter}
public class Order { private Long id; private Long userId; private Long itemId; private Integer quantity; private BigDecimal totalPrice; private Date createTime; // getter and setter}
3. 创建 DAO 层
创建三个 DAO 层接口,分别用于操作 'user'、'item' 和 'order' 表。javapublic interface UserDao { User getById(Long id); User getByUsername(String username); void save(User user);}
public interface ItemDao { Item getById(Long id); void updateQuantity(Long id, Integer quantity);}
public interface OrderDao { void save(Order order); List
4. 创建 Service 层
创建 UserService 和 ItemService 接口,分别处理用户和商品相关的业务逻辑。javapublic interface UserService { User getById(Long id); User getByUsername(String username); void save(User user); void buyItem(Long userId, Long itemId, Integer quantity);}
public interface ItemService { Item getById(Long id); void updateQuantity(Long id, Integer quantity); List
5. 实现 Service 层逻辑java@Servicepublic class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Autowired private ItemDao itemDao; @Autowired private OrderDao orderDao;
@Override public void buyItem(Long userId, Long itemId, Integer quantity) { User user = userDao.getById(userId); Item item = itemDao.getById(itemId);
if (user != null && item != null && item.getQuantity() >= quantity) { BigDecimal totalPrice = item.getPrice().multiply(new BigDecimal(quantity)); // 更新物品数量 itemDao.updateQuantity(itemId, item.getQuantity() - quantity);
// 创建订单 Order order = new Order(); order.setUserId(userId); order.setItemId(itemId); order.setQuantity(quantity); order.setTotalPrice(totalPrice); orderDao.save(order); } } // ... 其他方法实现}
@Servicepublic class ItemServiceImpl implements ItemService { @Autowired private ItemDao itemDao; @Autowired private OrderDao orderDao;
@Override public List<Order> getOrderList(Long itemId) { return orderDao.findByItemId(itemId); } // ... 其他方法实现}
6. 创建 Controller 层
创建 UserController 和 ItemController,提供 RESTful API 接口。java@RestController@RequestMapping('/api/users')public class UserController { @Autowired private UserService userService;
@PostMapping('/{userId}/buyItem') public void buyItem(@PathVariable Long userId, @RequestParam Long itemId, @RequestParam Integer quantity) { userService.buyItem(userId, itemId, quantity); } // ... 其他方法实现}
@RestController@RequestMapping('/api/items')public class ItemController { @Autowired private ItemService itemService;
@GetMapping('/{itemId}/orders') public List<Order> orderList(@PathVariable Long itemId) { return itemService.getOrderList(itemId); } // ... 其他方法实现}
7. 实现 DAO 层方法
使用 JdbcTemplate 或其他持久层框架实现 DAO 层接口,例如:java@Repositorypublic class OrderDaoImpl implements OrderDao { @Autowired private JdbcTemplate jdbcTemplate;
@Override public void save(Order order) { String sql = 'INSERT INTO `order`(user_id, item_id, quantity, total_price) VALUES (?, ?, ?, ?)'; jdbcTemplate.update(sql, order.getUserId(), order.getItemId(), order.getQuantity(), order.getTotalPrice()); }
@Override public List<Order> findByItemId(Long itemId) { String sql = 'SELECT * FROM `order` WHERE item_id = ?'; return jdbcTemplate.query(sql, new Object[]{itemId}, new BeanPropertyRowMapper<>(Order.class)); }}
8. 测试
使用 Postman 等工具测试 API 接口:
- 用户购买:发送 POST 请求到
/api/users/{userId}/buyItem,参数:itemId,quantity。* 商家查看订单:发送 GET 请求到/api/items/{itemId}/orders。
总结
本教程介绍了使用 Spring Boot 和 MySQL 实现用户购买及商家查看订单功能的基本步骤,您可以根据实际需求扩展功能,例如添加用户认证、支付集成等
原文地址: http://www.cveoy.top/t/topic/gTUq 著作权归作者所有。请勿转载和采集!