注解
@Data相当于类中有get与set方法
@NoArgsConstructor:相当于类中有无参构造器
@AllArgsConstructor:相当于类中有有参构造器
@Repository:使用@Repository注解可以确保DAO或者repositories提供异常转译,这个注解修饰的DAO或者repositories类会被ComponetScan发现并配置,同时也不需要为它们提供XML配置项。
@Autowired:自动导入依赖bean
1:Department表
@Data
@NoArgsConstructor
public class Department {
private Integer id;
private String departmentName;
public Department(Integer id,String departmentName){
this.id=id;
this.departmentName=departmentName;
}
}
2:Employee表
@Data
@AllArgsConstructor
@NoArgsConstructor//无参
public class Employee {
private Integer id;
private String lastName;
private String email;
private int sex;//0表示女,1表示男
private Department department;
private Date birth;
public Employee(Integer id, String lastName, String email, int sex, Department department) {
this.id = id;
this.lastName = lastName;
this.email = email;
this.sex = sex;
this.department = department;
this.birth = new Date();
}
}
3:EmployeeDao
Collection类
//员工Dao
@Repository
public class EmployeeDao {
private static Map<Integer, Employee> employees=null;
@Autowired
private DepartmentDao departmentDao;
static{
employees=new HashMap<Integer,Employee>();
employees.put(1001,new Employee
(1001,"sheepbotany","A2464018412@qq.com",0,new Department(101,"教学部")));
employees.put(1002,new Employee
(1002,"sheep","B2464018412@qq.com",0,new Department(102,"市场部")));
employees.put(1003,new Employee
(1003,"botany","C2464018412@qq.com",0,new Department(103,"教研部")));
employees.put(1004,new Employee
(1004,"wood","D2464018412@qq.com",1,new Department(104,"运营部")));
employees.put(1005,new Employee
(1005,"woodwhale","E2464018412@qq.com",1,new Department(105,"后勤部")));
}
//主键自增
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 getElementById(Integer id) {
return employees.get(id);
}
//删除员工
public void delete(Integer id){
employees.remove(id);
}
}
4:DepartmentDao
@Repository
public class DepartmentDao {
//模拟数据库中的数据
private static Map<Integer, Department> departments=null;
static{
//创建一个部门表
departments=new HashMap<Integer,Department>();
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);
}
}