????????本文使用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進階——注解一文全懂 → |