用JavaEE框架技术 完成:模拟购书的场景,书店有书若干本,当把一本书加入购物车,购物车中的书多了一本,而书店中的图书减少一本,这两件事共同构成一个事务。 请建立书店表和购物车表,对上述场景的业务逻辑建模并进行单元测试
时间: 2024-10-24 16:04:20 浏览: 43
在JavaEE框架下,我们可以使用Spring Boot和Hibernate等工具来完成这个购书场景的模拟,并利用JPA (Java Persistence API) 进行数据库操作。首先,我们需要创建两个实体类,分别是`Book`和`ShoppingCart`,以及对应的领域模型。
1. **书店表(Book.java)**:
```java
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private int stock;
// getter 和 setter 方法
}
```
2. **购物车表(ShoppingCartItem.java)**:
```java
@Entity
public class ShoppingCartItem {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="book_id")
private Book book;
private int quantity;
// 构造函数、getter 和 setter 方法
}
```
3. **购物车服务(ShoppingCartService.java)**:
```java
@Service
public class ShoppingCartService {
@Autowired
private BookRepository bookRepository;
@Autowired
private ShoppingCartItemRepository cartItemRepository;
public void addToCart(Long bookId, int quantity) {
Book book = bookRepository.findById(bookId).orElseThrow(() -> new ResourceNotFoundException("Book not found"));
if (book.getStock() < quantity) {
throw new InsufficientStockException();
}
// 减少库存
book.setStock(book.getStock() - quantity);
bookRepository.save(book);
// 添加到购物车
ShoppingCartItem cartItem = new ShoppingCartItem();
cartItem.setBook(book);
cartItem.setQuantity(quantity);
cartItemRepository.save(cartItem);
}
// 其他相关方法...
}
```
4. **单元测试(ShoppingCartServiceTest.java)**:
```java
@RunWith(SpringRunner.class)
@SpringBootTest
public class ShoppingCartServiceTest {
@Autowired
private ShoppingCartService service;
@Test
public void testAddToCart() {
// 创建数据并预设库存
Book book = new Book("Title", 10);
bookRepository.save(book);
try {
service.addToCart(book.getId(), 5);
Assert.assertEquals(book.getStock(), 5); // 库存应减为5
List<ShoppingCartItem> cartItems = cartItemRepository.findByBook(book);
assertEquals(1, cartItems.size()); // 购物车有一条记录
} finally {
bookRepository.delete(book);
}
}
阅读全文