看B站狂神视频学到的后台DAO层模拟数据的方法
在工程中创建pojo实体类和Dao类
(1)Department.java
// 部门表 @Data @AllArgsConstructor @NoArgsConstructor public class Department { private Integer id; private String departmentName; }上面的@data用于自动生成get、set方法,
@AllArgsConstructor、@NoArgsConstructor分别用于生成有参构造和无参构造
(2)Employee.java
@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; 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(); } }上面代码添加有参构造注解是因为日期要自动生成,因此在有参构造中自动生成日期。
(3)DepartmentDao
通过Map接口的key,value存储数据,
初始数据放在静态代码块中static{}
//部门dao @Repository public class DepartmentDao { private static Map<Integer, Department> departments = null; static { departments = new HashMap<>(); departments.put(101, new Department(101, "教学部")); departments.put(102, new Department(102, "市场部")); departments.put(103, new Department(103, "教研部")); departments.put(104, new Department(104, "运营部")); departments.put(105, new Department(105, "后勤部")); } //获得所有部门信息 public Collection<Department> getDepartments() { return departments.values(); } //根据id获取部门 public Department getDepartmentById(Integer id) { return departments.get(id); } }(4)EmployeeDao
需要注意的是: a、由于员工是属于某个部门的,因此要在EmployeeDao和DepartmentDao中添加@Repository注解,使其成为spring的bean,
然后就可以使用@Autowired将DepartmentDao注入进去。
b、由于主键是自增的,因此设置静态变量initId来达到添加员工自增id的目的。
//员工表 @Repository public class EmployeeDao { private static Map<Integer, Employee> employees = null; @Autowired private DepartmentDao departmentDao; static { employees = new HashMap<>(); employees.put(1001, new Employee(1001, "AAA", "A123123214@qq.com", 0, new Department(1001, "教学部"))); employees.put(1002, new Employee(1002, "BBB", "B123123214@qq.com", 1, new Department(1002, "市场部"))); employees.put(1003, new Employee(1003, "CCC", "C123123214@qq.com", 0, new Department(1003, "教研部"))); employees.put(1004, new Employee(1004, "DDD", "D123123214@qq.com", 1, new Department(1004, "运营部"))); employees.put(1005, new Employee(1005, "EEE", "E123123214@qq.com", 0, new Department(1005, "后勤部"))); } private static Integer initId = 1006; //添加员工 public void save(Employee employee) { if (employee.getId() != null) { employee.setId(initId++); } employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId())); employees.put(employee.getId(), employee); } //获得所有员工信息 public Collection<Employee> getAll() { return employees.values(); } //根据id获取员工信息 public Employee getEmployeeById(Integer id) { return employees.get(id); } //删除员工信息 public void delete(Integer id) { employees.remove(id); } }