怎么写一个基于spring boot的水果表包括价格名称数量详细代码介绍
以下是一个基于Spring Boot的水果表的示例代码:
首先,我们需要创建一个Fruit实体类,用于表示水果的属性:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Fruit {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
private int quantity;
// 构造函数、getter和setter方法
public Fruit() {
}
public Fruit(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
// getter和setter方法...
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 int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
接下来,我们需要创建一个FruitRepository接口,用于管理水果表的数据访问:
import org.springframework.data.jpa.repository.JpaRepository;
public interface FruitRepository extends JpaRepository<Fruit, Long> {
}
然后,我们创建一个FruitController类,用于处理水果表的HTTP请求:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/fruits")
public class FruitController {
private final FruitRepository fruitRepository;
@Autowired
public FruitController(FruitRepository fruitRepository) {
this.fruitRepository = fruitRepository;
}
@GetMapping
public List<Fruit> getAllFruits() {
return fruitRepository.findAll();
}
@GetMapping("/{id}")
public Fruit getFruitById(@PathVariable Long id) {
return fruitRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Fruit not found with id " + id));
}
@PostMapping
public Fruit createFruit(@RequestBody Fruit fruit) {
return fruitRepository.save(fruit);
}
@PutMapping("/{id}")
public Fruit updateFruit(@PathVariable Long id, @RequestBody Fruit updatedFruit) {
Fruit fruit = fruitRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Fruit not found with id " + id));
fruit.setName(updatedFruit.getName());
fruit.setPrice(updatedFruit.getPrice());
fruit.setQuantity(updatedFruit.getQuantity());
return fruitRepository.save(fruit);
}
@DeleteMapping("/{id}")
public void deleteFruit(@PathVariable Long id) {
fruitRepository.deleteById(id);
}
}
最后,我们创建一个SpringBootApplication类,用于启动Spring Boot应用:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class FruitApplication {
public static void main(String[] args) {
SpringApplication.run(FruitApplication.class, args);
}
}
这样,我们就创建了一个基于Spring Boot的水果表。你可以通过发送HTTP请求来访问和操作水果表的数据
原文地址: http://www.cveoy.top/t/topic/iXRt 著作权归作者所有。请勿转载和采集!