使用spring boot 写一个curd的类
时间: 2024-05-20 07:16:44 浏览: 127
spring3+hibernate4+maven=springMVC(curd)
4星 · 用户满意度95%
以下是一个使用Spring Boot进行CURD操作的示例:
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String name;
@NotNull
private String email;
public Employee() {}
public Employee(String name, String email) {
this.name = name;
this.email = email;
}
// getters and setters
}
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {}
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
public Employee getEmployeeById(Long id) {
return employeeRepository.findById(id).orElse(null);
}
public Employee addEmployee(Employee employee) {
return employeeRepository.save(employee);
}
public Employee updateEmployee(Employee employee) {
Employee existingEmployee = employeeRepository.findById(employee.getId()).orElse(null);
if (existingEmployee != null) {
existingEmployee.setName(employee.getName());
existingEmployee.setEmail(employee.getEmail());
return employeeRepository.save(existingEmployee);
}
return null;
}
public void deleteEmployee(Long id) {
employeeRepository.deleteById(id);
}
}
@RestController
@RequestMapping("/api")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeService.getAllEmployees();
}
@GetMapping("/employees/{id}")
public Employee getEmployeeById(@PathVariable Long id) {
return employeeService.getEmployeeById(id);
}
@PostMapping("/employees")
public Employee addEmployee(@RequestBody Employee employee) {
return employeeService.addEmployee(employee);
}
@PutMapping("/employees/{id}")
public Employee updateEmployee(@RequestBody Employee employee, @PathVariable Long id) {
employee.setId(id);
return employeeService.updateEmployee(employee);
}
@DeleteMapping("/employees/{id}")
public void deleteEmployee(@PathVariable Long id) {
employeeService.deleteEmployee(id);
}
}
在这个示例中,我们定义了一个Employee实体类,一个EmployeeRepository接口来操作数据库,一个EmployeeService类来实现业务逻辑,并在EmployeeController中暴露了RESTful API来处理HTTP请求。您可以根据您的需求修改这个示例,例如更改实体类的属性或更改API的路径。
阅读全文