|
| 1 | +package com.java.demo03; |
| 2 | + |
| 3 | +/** |
| 4 | + * 数据表与简单java类 : 一对多 |
| 5 | + * 还有多对多,类似的,就没有写了 |
| 6 | + * |
| 7 | + * |
| 8 | + * @author jack w |
| 9 | + * |
| 10 | + */ |
| 11 | + |
| 12 | +class Employee { |
| 13 | + private Integer empId; |
| 14 | + private String name; |
| 15 | + private Double salary; |
| 16 | + |
| 17 | + private Department department; |
| 18 | + private Employee manager; |
| 19 | + |
| 20 | + public Employee() { |
| 21 | + |
| 22 | + } |
| 23 | + |
| 24 | + public Employee(Integer empId, String name, Double salary) { |
| 25 | + this.empId = empId; |
| 26 | + this.name = name; |
| 27 | + this.salary = salary; |
| 28 | + } |
| 29 | + |
| 30 | + public void setDepartment(Department department) { |
| 31 | + this.department = department; |
| 32 | + } |
| 33 | + |
| 34 | + public Department getDepartment() { |
| 35 | + return department; |
| 36 | + } |
| 37 | + |
| 38 | + public void setManager(Employee manager) { |
| 39 | + this.manager = manager; |
| 40 | + } |
| 41 | + |
| 42 | + public Employee getManager() { |
| 43 | + return manager; |
| 44 | + } |
| 45 | + |
| 46 | + @Override |
| 47 | + public String toString() { |
| 48 | + return "Employee [empId=" + empId + ", name=" + name + ", salary=" + salary + ", department=" + department |
| 49 | + + ", manager=" + manager + "]"; |
| 50 | + } |
| 51 | + |
| 52 | + |
| 53 | +} |
| 54 | + |
| 55 | +class Department { |
| 56 | + private Integer deptId; |
| 57 | + private String deptName; |
| 58 | + |
| 59 | + private Employee[] employees; |
| 60 | + |
| 61 | + public Department() { |
| 62 | + |
| 63 | + } |
| 64 | + |
| 65 | + public Department(Integer deptId, String deptName) { |
| 66 | + this.deptId = deptId; |
| 67 | + this.deptName = deptName; |
| 68 | + } |
| 69 | + |
| 70 | + public void setEmployees(Employee[] employees) { |
| 71 | + this.employees = employees; |
| 72 | + } |
| 73 | + public Employee[] getEmployees() { |
| 74 | + return employees; |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +public class OneToMany { |
| 79 | + public static void main(String[] args) { |
| 80 | + |
| 81 | + Employee emp1 = new Employee(1001, "jack", 1000.00); |
| 82 | + Employee emp2 = new Employee(1002, "smith", 2000.00); |
| 83 | + Employee emp3 = new Employee(1003, "tom", 4000.00); |
| 84 | + Department dept1 = new Department(1, "技术部"); |
| 85 | + Department dept2 = new Department(2, "产品部"); |
| 86 | + |
| 87 | + emp1.setDepartment(dept1); |
| 88 | + emp1.setManager(emp3); |
| 89 | + emp2.setDepartment(dept2); |
| 90 | + emp2.setManager(emp3); |
| 91 | + emp3.setDepartment(dept2); |
| 92 | + |
| 93 | + dept1.setEmployees(new Employee[]{emp1}); |
| 94 | + dept2.setEmployees(new Employee[]{emp2,emp3}); |
| 95 | + |
| 96 | + for (int i = 0; i < dept1.getEmployees().length; i++) { |
| 97 | + System.out.println(dept1.getEmployees()[i].toString()); |
| 98 | + } |
| 99 | + } |
| 100 | +} |
0 commit comments