Spring Boot 水果表 CRUD 业务逻辑层代码示例
以下是一个简单的 Spring Boot 项目业务逻辑层代码示例,用于管理水果表 (名称,价格,数量):
@Service
public class FruitService {
@Autowired
private FruitRepository fruitRepository;
public List<Fruit> getAllFruits() {
return fruitRepository.findAll();
}
public Fruit getFruitById(Long id) {
return fruitRepository.findById(id)
.orElseThrow(() -> new NotFoundException('Fruit not found with id: ' + id));
}
public Fruit createFruit(Fruit fruit) {
return fruitRepository.save(fruit);
}
public Fruit updateFruit(Long id, Fruit updatedFruit) {
Fruit fruit = getFruitById(id);
fruit.setName(updatedFruit.getName());
fruit.setPrice(updatedFruit.getPrice());
fruit.setQuantity(updatedFruit.getQuantity());
return fruitRepository.save(fruit);
}
public void deleteFruit(Long id) {
Fruit fruit = getFruitById(id);
fruitRepository.delete(fruit);
}
}
上述代码中的 FruitService 类使用了 @Service 注解,将其标记为 Spring 的服务组件。该类通过自动装配 FruitRepository,实现对水果表的 CRUD 操作。
getAllFruits 方法返回所有水果的列表。
getFruitById 方法根据给定的 id 返回对应的水果对象,如果找不到对应的水果,则抛出 NotFoundException 异常。
createFruit 方法创建一个新的水果对象并保存到数据库。
updateFruit 方法根据给定的 id 更新水果对象的名称、价格和数量,并保存到数据库。
deleteFruit 方法根据给定的 id 删除对应的水果对象。
需要注意的是,上述代码中的 FruitRepository 是一个自定义的接口,用于与数据库进行交互。你需要根据自己的数据库配置和需求来实现该接口。
原文地址: https://www.cveoy.top/t/topic/qEZf 著作权归作者所有。请勿转载和采集!