springboot229基于Spring Boot的企业员工薪酬关系系统的设计
由于原始代码已经非常接近完整,以下是核心函数的示例,展示了如何使用Spring Data JPA和Spring Security实现员工信息的查询和修改:
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
@Autowired
private DepartmentRepository departmentRepository;
@Autowired
private PositionRepository positionRepository;
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
public Employee getEmployeeById(Long id) {
return employeeRepository.findById(id).orElse(null);
}
@Transactional
public Employee updateEmployee(Long id, EmployeeDto employeeDto) {
Employee employee = employeeRepository.findById(id).orElseThrow(() -> new RuntimeException("Employee not found"));
Department department = departmentRepository.findById(employeeDto.getDepartment().getId())
.orElseThrow(() -> new RuntimeException("Department not found"));
Position position = positionRepository.findById(employeeDto.getPosition().getId())
.orElseThrow(() -> new RuntimeException("Position not found"));
employee.setName(employeeDto.getName());
employee.setDepartment(department);
employee.setPosition(position);
employee.setHireDate(employeeDto.getHireDate());
employee.setPhoneNumber(employeeDto.getPhoneNumber());
employee.setEmail(employeeDto.getEmail());
employee.setEnabled(employeeDto.isEnabled());
return employeeRepository.save(employee);
}
// ... 其他方法略 ...
}
在这个示例中,我们定义了一个服务类EmployeeService
,它使用自动装配的EmployeeRepository
来查询和保存员工信息。updateEmployee
方法接收一个员工ID和一个DTO对象,然后根据DTO中的信息更新对应员工的信息。这里使用了Spring Data JPA的查询方法findById
,以及Spring的事务管理注解@Transactional
来确保更新操作的完整性。
评论已关闭