JavaEE员工管理系统代码实现
时间: 2023-12-07 08:04:11 浏览: 136
14.基于JavaEE-仓库管理系统源码
为了方便演示,本示例使用Spring Boot框架来实现JavaEE员工管理系统。以下是代码实现的步骤:
1. 创建Spring Boot项目
使用Spring Initializr来创建一个新的Spring Boot项目,添加以下依赖:
- Spring Web:用于创建RESTful服务
- Spring Data JPA:用于操作数据库
- MySQL Driver:用于连接MySQL数据库
2. 创建数据表
在MySQL数据库中创建一个名为“employee”的数据表,包括以下字段:
- id:员工ID,自增长
- name:员工姓名,长度为50
- age:员工年龄,长度为3
- gender:员工性别,长度为10
- department:员工部门,长度为50
3. 创建实体类
创建一个名为“Employee”的实体类,包括以上数据表中的字段,并添加相应的注解。
4. 创建数据访问层
创建一个名为“EmployeeRepository”的接口,继承自JpaRepository,并添加相应的注解。
5. 创建服务层
创建一个名为“EmployeeService”的服务类,实现以下方法:
- findAll():查询所有员工
- findById(Long id):根据ID查询员工
- save(Employee employee):保存员工
- deleteById(Long id):根据ID删除员工
6. 创建控制器
创建一个名为“EmployeeController”的控制器类,实现以下接口:
- GET /employees:查询所有员工
- GET /employees/{id}:根据ID查询员工
- POST /employees:保存员工
- DELETE /employees/{id}:根据ID删除员工
7. 测试
使用Postman等工具测试以上接口是否正常工作。
完整代码如下:
Employee.java
```java
import javax.persistence.*;
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 50)
private String name;
@Column(length = 3)
private Integer age;
@Column(length = 10)
private String gender;
@Column(length = 50)
private String department;
// getters and setters
}
```
EmployeeRepository.java
```java
import org.springframework.data.jpa.repository.JpaRepository;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
```
EmployeeService.java
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class EmployeeService {
private final EmployeeRepository employeeRepository;
@Autowired
public EmployeeService(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
public List<Employee> findAll() {
return employeeRepository.findAll();
}
public Employee findById(Long id) {
return employeeRepository.findById(id).orElse(null);
}
public Employee save(Employee employee) {
return employeeRepository.save(employee);
}
public void deleteById(Long id) {
employeeRepository.deleteById(id);
}
}
```
EmployeeController.java
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/employees")
public class EmployeeController {
private final EmployeeService employeeService;
@Autowired
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@GetMapping
public List<Employee> findAll() {
return employeeService.findAll();
}
@GetMapping("/{id}")
public Employee findById(@PathVariable Long id) {
return employeeService.findById(id);
}
@PostMapping
public Employee save(@RequestBody Employee employee) {
return employeeService.save(employee);
}
@DeleteMapping("/{id}")
public void deleteById(@PathVariable Long id) {
employeeService.deleteById(id);
}
}
```
阅读全文