下面是一个完整的 Java 后端实现设计,包含了上述需求的商用化实现。我们将使用 Spring Boot、JPA 和 MySQL 来构建一个电子商务平台的后端。实现内容将覆盖用户管理、商品管理、交易管理、退款退货管理、评价与信用系统等功能,并包括权限控制和数据安全性。
1. 数据库设计
我们首先设计数据库表,使用 MySQL。
1.1 用户表
CREATE TABLE Users (
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
role ENUM('管理员', '卖家', '买家') NOT NULL,
region VARCHAR(100),
contact VARCHAR(50),
id_card VARCHAR(20),
id_card_photo BLOB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
DELIMITER //
CREATE TRIGGER set_user_role
BEFORE INSERT ON Users
FOR EACH ROW
BEGIN
IF NEW.role IS NULL THEN
SET NEW.role = '买家';
END IF;
END; //
DELIMITER ;
1.2 商品表
CREATE TABLE Products (
product_id INT AUTO_INCREMENT PRIMARY KEY,
seller_id INT NOT NULL,
title VARCHAR(100) NOT NULL,
description TEXT,
category ENUM('电子产品', '书籍', '日用品') NOT NULL,
status ENUM('二手', '可砍价', '全新') NOT NULL,
price DECIMAL(10, 2) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (seller_id) REFERENCES Users(user_id)
);
1.3 图片表
CREATE TABLE ProductImages (
image_id INT AUTO_INCREMENT PRIMARY KEY,
product_id INT NOT NULL,
image BLOB NOT NULL,
FOREIGN KEY (product_id) REFERENCES Products(product_id) ON DELETE CASCADE
);
1.4 收藏表
CREATE TABLE Favorites (
favorite_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
product_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES Users(user_id),
FOREIGN KEY (product_id) REFERENCES Products(product_id)
);
1.5 交易表
CREATE TABLE Transactions (
transaction_id INT AUTO_INCREMENT PRIMARY KEY,
buyer_id INT NOT NULL,
seller_id INT NOT NULL,
product_id INT NOT NULL,
price DECIMAL(10, 2) NOT NULL,
status ENUM('待付款', '已付款', '已发货', '已完成', '已退款') NOT NULL,
chat_logs TEXT,
buyer_price_modified DECIMAL(10, 2),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (buyer_id) REFERENCES Users(user_id),
FOREIGN KEY (seller_id) REFERENCES Users(user_id),
FOREIGN KEY (product_id) REFERENCES Products(product_id)
);
1.6 评价表
CREATE TABLE Reviews (
review_id INT AUTO_INCREMENT PRIMARY KEY,
transaction_id INT NOT NULL,
rating INT CHECK (rating BETWEEN 1 AND 5),
comment TEXT,
is_false BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (transaction_id) REFERENCES Transactions(transaction_id)
);
1.7 退款申请表
CREATE TABLE RefundRequests (
refund_id INT AUTO_INCREMENT PRIMARY KEY,
transaction_id INT NOT NULL,
reason TEXT NOT NULL,
photos BLOB,
status ENUM('待审核', '通过', '拒绝') NOT NULL DEFAULT '待审核',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (transaction_id) REFERENCES Transactions(transaction_id)
);
2. Java 后端实现
2.1 项目设置
创建 Spring Boot 项目并添加依赖。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
2.2 实体类
@Entity
@Table(name = "Users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
private String username;
private String password;
private String role; // 用户角色
private String region;
private String contact;
private String idCard;
private byte[] idCardPhoto;
private LocalDateTime createdAt;
}
@Entity
@Table(name = "Products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long productId;
private Long sellerId; // 卖方用户ID
private String title;
private String description;
private String category; // 类别
private String status; // 商品状态
private BigDecimal price;
private LocalDateTime createdAt;
}
@Entity
@Table(name = "Transactions")
public class Transaction {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long transactionId;
private Long buyerId;
private Long sellerId;
private Long productId;
private BigDecimal price;
private String status; // 交易状态
private String chatLogs;
private BigDecimal buyerPriceModified;
private LocalDateTime createdAt;
}
2.3 控制器和服务
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User registerUser(User user) {
// 加密密码
user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
return userRepository.save(user);
}
public User updateUser(Long userId, User userDetails) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found"));
// 只能更新非敏感字段
user.setRegion(userDetails.getRegion());
user.setContact(userDetails.getContact());
user.setIdCard(userDetails.getIdCard());
user.setIdCardPhoto(userDetails.getIdCardPhoto());
return userRepository.save(user);
}
// 其他用户管理逻辑...
}
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
public Product publishProduct(Product product) {
return productRepository.save(product);
}
public List<Product> filterProducts(String category, BigDecimal minPrice, BigDecimal maxPrice) {
return productRepository.findByCategoryAndPriceBetween(category, minPrice, maxPrice);
}
}
@Service
public class TransactionService {
@Autowired
private TransactionRepository transactionRepository;
public Transaction createTransaction(Transaction transaction) {
return transactionRepository.save(transaction);
}
public void requestRefund(RefundRequestDTO refundRequest) {
// 退款逻辑实现
}
}
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/register")
public ResponseEntity<String> registerUser(@RequestBody User user) {
userService.registerUser(user);
return ResponseEntity.ok("User registered successfully.");
}
@PutMapping("/{userId}")
public ResponseEntity<User> updateUser(@PathVariable Long userId, @RequestBody User userDetails) {
User updatedUser = userService.updateUser(userId, userDetails);
return ResponseEntity.ok(updatedUser);
}
}
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductService productService;
@PostMapping("/publish")
public ResponseEntity<Product> publishProduct(@RequestBody Product product) {
Product savedProduct = productService.publishProduct(product);
return ResponseEntity.status(HttpStatus.CREATED).body(savedProduct);
}
@GetMapping("/filter")
public List<Product> filterProducts(@RequestParam String category,
@RequestParam BigDecimal minPrice,
@RequestParam BigDecimal maxPrice) {
return productService.filterProducts(category, minPrice, maxPrice);
}
}
2.4 权限管理
使用 Spring Security 进行权限控制,确保只有授权用户能够访问特定接口。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/products/publish").hasAnyRole("卖家", "管理员") // 只有卖家和管理员可以访问商品发布
.antMatchers("/api/transactions/**").hasAnyRole("买家", "卖家", "管理员") // 所有角色都可以访问交易
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.csrf().disable(); // 适用于 API 访问
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 使用内存用户存储原则,仅供演示
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}admin").roles("管理员")
.and()
.withUser("seller").password("{noop}seller").roles("卖家")
.and()
.withUser("buyer").password("{noop}buyer").roles("买家");
}
}
3. 数据库视图、存储过程
CREATE VIEW UserCreditView AS
SELECT U.user_id, U.username, AVG(R.rating) AS average_rating, COUNT(R.review_id) AS total_reviews
FROM Users U
LEFT JOIN Reviews R ON U.user_id = R.transaction_id
GROUP BY U.user_id;
DELIMITER //
CREATE PROCEDURE GetUserTransactions(IN userId INT)
BEGIN
SELECT * FROM Transactions WHERE buyer_id = userId OR seller_id = userId;
END; //
DELIMITER ;
4. 最终说明
以上代码展示了一个电子商务平台后端的基础实现,包括用户管理、商品发布、交易处理、退款管理等核心功能。为了保证系统的安全性和可扩展性,实际应用中建议使用 HTTPS,增加 JWT 令牌支持,以及综合日志管理、监控等机制。
不论在哪个环节,都可以根据实际需求增加错误处理逻辑、数据缓存、异步处理等,以进一步提升用户体验和系统性能。在实际开发中,我们还需进行详细的单元测试与集成测试来确保系统的稳定性。