利用SSM框架实现一个员工管理系统要求实现:1、查询所有员工 2、删除员工
时间: 2024-11-17 13:28:40 浏览: 10
利用Spring Security (SSM)框架构建一个员工管理系统,首先需要设置好Spring Boot作为基础架构,整合Spring MVC进行Web应用开发,加上MyBatis做数据访问层。以下是实现查询所有员工和删除员工操作的基本步骤:
1. **配置Spring Data JPA** 或 **MyBatis**:
- 如果选择JPA,你需要创建一个`Employee`实体类,并在Repository接口中声明查询所有员工的方法,如`List<Employee> findAll()`。
- 如果选择MyBatis,创建一个`EmployeeMapper`接口并定义查询方法,如`List<Employee> selectAllEmployees()`。
```java
// Employee实体类
public class Employee {
private Long id;
private String name;
// getters and setters...
}
// EmployeeRepository接口(JPA)
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
List<Employee> findAll();
}
// EmployeeMapper接口(MyBatis)
public interface EmployeeMapper {
@Select("SELECT * FROM employee")
List<Employee> selectAllEmployees();
}
```
2. **控制器层(Controller)**:
创建一个控制器类,注入对应的数据访问组件,处理HTTP请求。
```java
@RestController
@RequestMapping("/employees")
public class EmployeeController {
private final EmployeeRepository repository; // or EmployeeMapper mapper;
public EmployeeController(EmployeeRepository repository) {
this.repository = repository;
}
// 查询所有员工
@GetMapping
public ResponseEntity<List<Employee>> getAllEmployees() {
try {
return new ResponseEntity<>(repository.findAll(), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
// 删除员工
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteEmployee(@PathVariable Long id) {
Optional<Employee> employee = repository.findById(id);
if (employee.isPresent()) {
repository.delete(employee.get());
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} else {
return new ResponseEntity<>("Employee not found", HttpStatus.NOT_FOUND);
}
}
}
```
阅读全文