本文使用SpringBoot进行电商系统商品数据增删改查的简单开发流程。
本文目录
- 一、创建Spring Boot项目
- 二、配置数据库连接
- 三、创建实体类
- 四、创建Repository接口
- 五、创建Service层
- 六、创建Controller层
- 七、测试
一、创建Spring Boot项目
可以通过https://start.spring.io/或者IDEA创建,需添加对应的依赖
<!-- JPA --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><!-- 数据库驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!--web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
二、配置数据库连接
在 src/main/resources
目录下找到 application.properties
文件,添加数据库连接配置,用户名和密码自行修改:
spring.datasource.url=jdbc:mysql://localhost:3306/ecommerce?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=用户名
spring.datasource.password=密码
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
三、创建实体类
在 src/main/java
目录下创建实体类 Product
,用于表示商品数据:
package com.example.ecommerceproduct.entity;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;@Entity
public class Product {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String name;private double price;private String description;// 无参构造函数public Product() {}// 有参构造函数public Product(String name, double price, String description) {this.name = name;this.price = price;this.description = description;}public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}
}
这里可以使用lombok简化实体类
实体对应sql
CREATE TABLE IF NOT EXISTS Product (-- 商品IDid BIGINT AUTO_INCREMENT PRIMARY KEY,-- 商品名称name VARCHAR(255) NOT NULL,-- 商品价格price DECIMAL(10, 2) NOT NULL,-- 商品描述description char(255)
);
并且预制了一些数据:
四、创建Repository接口
创建 ProductRepository
接口,用于与数据库进行交互:
package com.example.ecommerceproduct.repository;import com.example.ecommerceproduct.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;public interface ProductRepository extends JpaRepository<Product, Long> {
}
五、创建Service层
创建 ProductService
类,处理业务逻辑:
package com.example.ecommerceproduct.service;import com.example.ecommerceproduct.entity.Product;
import com.example.ecommerceproduct.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;
import java.util.Optional;@Service
public class ProductService {@Autowiredprivate ProductRepository productRepository;// 添加商品public Product addProduct(Product product) {return productRepository.save(product);}// 获取所有商品public List<Product> getAllProducts() {return productRepository.findAll();}// 根据ID获取商品public Optional<Product> getProductById(Long id) {return productRepository.findById(id);}// 更新商品信息public Product updateProduct(Long id, Product updatedProduct) {return productRepository.findById(id).map(product -> {product.setName(updatedProduct.getName());product.setPrice(updatedProduct.getPrice());product.setDescription(updatedProduct.getDescription());return productRepository.save(product);}).orElse(null);}// 删除商品public void deleteProduct(Long id) {productRepository.deleteById(id);}
}
六、创建Controller层
创建 ProductController
类,处理HTTP请求:
package com.example.ecommerceproduct.controller;import com.example.ecommerceproduct.entity.Product;
import com.example.ecommerceproduct.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;import java.util.List;
import java.util.Optional;@RestController
@RequestMapping("/api/products")
public class ProductController {@Autowiredprivate ProductService productService;// 添加商品@PostMappingpublic ResponseEntity<Product> addProduct(@RequestBody Product product) {Product savedProduct = productService.addProduct(product);return new ResponseEntity<>(savedProduct, HttpStatus.CREATED);}// 获取所有商品@GetMappingpublic ResponseEntity<List<Product>> getAllProducts() {List<Product> products = productService.getAllProducts();return new ResponseEntity<>(products, HttpStatus.OK);}// 根据ID获取商品@GetMapping("/{id}")public ResponseEntity<Product> getProductById(@PathVariable Long id) {Optional<Product> product = productService.getProductById(id);return product.map(value -> new ResponseEntity<>(value, HttpStatus.OK)).orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));}// 更新商品信息@PutMapping("/{id}")public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product updatedProduct) {Product product = productService.updateProduct(id, updatedProduct);if (product != null) {return new ResponseEntity<>(product, HttpStatus.OK);} else {return new ResponseEntity<>(HttpStatus.NOT_FOUND);}}// 删除商品@DeleteMapping("/{id}")public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {productService.deleteProduct(id);return new ResponseEntity<>(HttpStatus.NO_CONTENT);}
}
七、测试
启动Spring Boot应用程序,访问以下接口进行测试:
http://localhost:8080/api/products
可以看到操作的数据了,这样就完成了一个简单的Spring Boot电商系统商品数据增删改查的开发了,当然可以根据这些自行扩展需要实现的功能。
← 上一篇 Java进阶——Stream流以及常用方法详解 | 记得点赞、关注、收藏哦! | 下一篇 Java进阶——注解一文全懂 → |