spring boot实现加入购物车的代码
时间: 2023-10-30 21:24:45 浏览: 77
以下是一个简单的Spring Boot实现加入购物车的代码示例:
1. Cart实体类
```java
@Entity
@Table(name = "cart")
public class Cart {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "product_id", nullable = false)
private Product product;
private int quantity;
private double price;
// getters and setters
}
```
2. Product实体类
```java
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private double price;
// getters and setters
}
```
3. CartRepository接口
```java
@Repository
public interface CartRepository extends JpaRepository<Cart, Long> {
}
```
4. CartService类
```java
@Service
public class CartService {
@Autowired
private CartRepository cartRepository;
public void addToCart(Product product, int quantity) {
Cart cart = new Cart();
cart.setProduct(product);
cart.setQuantity(quantity);
cart.setPrice(product.getPrice() * quantity);
cartRepository.save(cart);
}
public void removeFromCart(Long cartId) {
cartRepository.deleteById(cartId);
}
public void updateCart(Long cartId, int quantity) {
Cart cart = cartRepository.findById(cartId).orElse(null);
if (cart != null) {
cart.setQuantity(quantity);
cart.setPrice(cart.getProduct().getPrice() * quantity);
cartRepository.save(cart);
}
}
public List<Cart> getCartItems() {
return cartRepository.findAll();
}
public double getTotalPrice() {
List<Cart> cartItems = cartRepository.findAll();
double totalPrice = 0.0;
for (Cart cart : cartItems) {
totalPrice += cart.getPrice();
}
return totalPrice;
}
}
```
5. CartController类
```java
@RestController
@RequestMapping("/cart")
public class CartController {
@Autowired
private CartService cartService;
@PostMapping("/add")
public void addToCart(@RequestParam Long productId, @RequestParam int quantity) {
Product product = productService.getProductById(productId);
cartService.addToCart(product, quantity);
}
@DeleteMapping("/{cartId}")
public void removeFromCart(@PathVariable Long cartId) {
cartService.removeFromCart(cartId);
}
@PutMapping("/{cartId}")
public void updateCart(@PathVariable Long cartId, @RequestParam int quantity) {
cartService.updateCart(cartId, quantity);
}
@GetMapping("/")
public List<Cart> getCartItems() {
return cartService.getCartItems();
}
@GetMapping("/total-price")
public double getTotalPrice() {
return cartService.getTotalPrice();
}
}
```
在以上代码中,我们使用了Spring Data JPA来实现数据访问,并使用了RESTful API来实现加入购物车、查看购物车、删除购物车等操作。此外,我们还使用了@Autowired注解来自动装配CartService和ProductService类。
阅读全文