Spring Boot 水果表项目:CRUD 操作示例
"使用 Spring Boot 和 JPA 创建一个简单的水果表项目,包含 CRUD 操作,并提供代码示例和说明。\n\n1. 创建一个 Spring Boot 项目,包括以下依赖项:\nxml\n<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-data-jpa</artifactId>\n</dependency>\n<dependency>\n <groupId>com.h2database</groupId>\n <artifactId>h2</artifactId>\n <scope>runtime</scope>\n</dependency>\n\n\n2. 创建一个名为 Fruit 的实体类,包含名称、价格、数量和 id 属性:\njava\n@Entity\n@Table(name = \"fruits\")\npublic class Fruit {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n private String name;\n\n private double price;\n\n private int quantity;\n\n // 省略构造函数、getter 和 setter 方法\n}\n\n\n3. 创建一个名为 FruitRepository 的接口,继承自 JpaRepository,用于对 Fruit 实体的数据库操作:\njava\n@Repository\npublic interface FruitRepository extends JpaRepository<Fruit, Long> {\n}\n\n\n4. 创建一个名为 FruitController 的控制器类,处理与水果表相关的 HTTP 请求:\njava\n@RestController\n@RequestMapping(\"/fruits\")\npublic class FruitController {\n @Autowired\n private FruitRepository fruitRepository;\n\n @GetMapping\n public List<Fruit> getAllFruits() {\n return fruitRepository.findAll();\n }\n\n @PostMapping\n public Fruit createFruit(@RequestBody Fruit fruit) {\n return fruitRepository.save(fruit);\n }\n\n @GetMapping(\"/{id}\")\n public Fruit getFruitById(@PathVariable Long id) {\n return fruitRepository.findById(id)\n .orElseThrow(() -> new ResourceNotFoundException(\"Fruit not found with id: \" + id));\n }\n\n @PutMapping(\"/{id}\")\n public Fruit updateFruit(@PathVariable Long id, @RequestBody Fruit fruitDetails) {\n Fruit fruit = fruitRepository.findById(id)\n .orElseThrow(() -> new ResourceNotFoundException(\"Fruit not found with id: \" + id));\n\n fruit.setName(fruitDetails.getName());\n fruit.setPrice(fruitDetails.getPrice());\n fruit.setQuantity(fruitDetails.getQuantity());\n\n return fruitRepository.save(fruit);\n }\n\n @DeleteMapping(\"/{id}\")\n public ResponseEntity<?> deleteFruit(@PathVariable Long id) {\n Fruit fruit = fruitRepository.findById(id)\n .orElseThrow(() -> new ResourceNotFoundException(\"Fruit not found with id: \" + id));\n\n fruitRepository.delete(fruit);\n return ResponseEntity.ok().build();\n }\n}\n\n\n5. 创建一个名为 ResourceNotFoundException 的异常类,用于处理资源未找到的情况:\njava\n@ResponseStatus(HttpStatus.NOT_FOUND)\npublic class ResourceNotFoundException extends RuntimeException {\n public ResourceNotFoundException(String message) {\n super(message);\n }\n}\n\n\n6. 运行 Spring Boot 应用程序,并使用 Postman 或类似的工具进行测试。\n\n这个示例项目实现了基本的 CRUD(创建、读取、更新、删除)操作,你可以根据实际需求进行扩展和修改。\n\n注意:\n\n* 该示例使用 H2 数据库进行测试,你可以根据需要更换为其他数据库。\n* 为了方便演示,代码省略了构造函数、getter 和 setter 方法,实际开发中需要根据需要进行补充。\n* 该示例仅供参考,实际项目中需要根据具体需求进行设计和实现。\n
原文地址: https://www.cveoy.top/t/topic/pTwf 著作权归作者所有。请勿转载和采集!