【狂神说Java】SpringBoot最新教程IDEA版通俗易懂20 ~ 28:员工管理系统
20、员工管理系统:准备工作
首先确定项目的结构:
从底层开始编写。
静态资源导入
(伪造)数据库
导入lombok,添加lombok依赖:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
编写部门表
// 部门表
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private Integer id ;
private String departmentName ;
}
编写员工表
@Data
@NoArgsConstructor
public class Employee {
private Integer id ;
private String lastName ;
private String email ;
private Integer sex ; // 0女、1男
private Department department ;
private Date birth ; // Date类用于描述日期信息
// 定义有参构造,为了让birth内部生成
public Employee(Integer id, String lastName, String email, Integer sex, Department department) {
this.id = id;
this.lastName = lastName;
this.email = email;
this.sex = sex;
this.department = department;
this.birth = new Date();
}
}
编写Dao层
部门
@Repository
public class DepartmentDao {
// 初始化数据:模拟数据库中的数据
// 在初始化时加载,需要static;库需要map实现
private static Map<Integer, Department> departments = null ;
// 下面赋初始值
static {
departments = new HashMap<>() ; // 创建一个部门表,JDK1.8之后泛型可省略
departments.put(1701, new Department(1701, "Fintech Department")) ;
departments.put(1702, new Department(1702, "Administrative Department")) ;
departments.put(1703, new Department(1703, "Human Resources Department")) ;
departments.put(1704, new Department(1704, "Department of trade and Finance")) ;
departments.put(1705, new Department(1705, "Retail Business Department")) ;
}
/* 数据库的增删查改 */
// 获得所有部门信息
public Collection<Department> getDepartments() {
return departments.values() ;
}
// 通过部门id得到部门信息
public Department getDepartmentById(Integer id) {
return departments.get(id) ;
}
}
员工
@Repository
public class EmployeeDao {
// 初始化数据:模拟数据库中的数据
// 在初始化时加载,需要static;库需要map实现
private static Map<Integer, Employee> employees = null ;
// 首先员工有所属部门
@Autowired // 可以使用DepartmentDao了
private DepartmentDao departmentDao ; // 这个操作要求这两个Dao被@Repository ➡ 被Spring托管
// 下面赋初始值
static {
employees = new HashMap<>() ; // 创建一个部门表,JDK1.8之后泛型可省略
employees.put(13001, new Employee(13001, "Hathway", "[email protected]", 0, new Department(1704, "Department of trade and Finance"))) ;
employees.put(13002, new Employee(13002, "Dexter", "[email protected]", 1, new Department(1701, "Fintech Department"))) ;
employees.put(13003, new Employee(13003, "Nana", "[email protected]", 0, new Department(1703, "Human Resources Department"))) ;
employees.put(13004, new Employee(13004, "Choco", "[email protected]", 0, new Department(1705, "Retail Dusiness Department"))) ;
employees.put(13005, new Employee(13005, "Tataki", "[email protected]", 1, new Department(1702, "Administrative Department"))) ;
// 因为static的原因,无法用departmentDao.getDepartmentById(Integer id)方法来获取部门
}
/* 增删查改 */
// 增加一个员工
private static Integer initId = 13006 ;
public void add(Employee employee) {
if (null == employee.getId()) {
employee.setId(initId++) ;
}
employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
employees.put(employee.getId()