这是一个一对多关系的javabean类,注意Student类中有一个School的参数。正常我们写javabean的时候只在School那方写一个set集合。Student写一个School,确实可以实现直接查找一个学生的学校是什么?
那是不是如果我们正常的javabean写法,只能再数据库中对外键进行数据的增加,并不能实现查找一个学生的所在学校的这个实现?
那如果hibernate时有这么写,那么是不是也不能实现?
其次,为什么我们在school.getAllStudent().add(new student()); 的时候,可以实现在数据库中对student表中外键的增加?
1 import java.util.*;
2 public class TestDemo{//设置学校和学生的关系
3 public static void main(String args[]){
4 School sch = new School("清华大学") ;//实例化学校对象
5 Student s1 = new Student("张三",21) ;//实例化学生对象
6 Student s2 = new Student("李四",22) ;
7 Student s3 = new Student("王五",23) ;
8 sch.getAllStudents().add(s1) ;//在学校中加入学生
9 sch.getAllStudents().add(s2) ;
10 sch.getAllStudents().add(s3) ;
11 s1.setSchool(sch) ;//一个学生属于一个学校
12 s2.setSchool(sch) ;
13 s3.setSchool(sch) ;
14 System.out.println(sch) ;
15 Iterator<Student> iter = sch.getAllStudents().iterator() ;
16 while(iter.hasNext()){
17 System.out.println("\t|- " + iter.next()) ;
18 }
19 }
20 }
21
22 //学生类
23 class Student{
24 private String name ;
25 private int age ;
26 private School school; // 一个学生属于一个学校
27 public Student(String name,int age){
28 this.setName(name) ;
29 this.setAge(age) ;
30 }
31 public void setSchool(School school){
32 this.school = school ;
33 }
34 public School getSchool(){
35 return this.school ;
36 }
37 public void setName(String name){
38 this.name = name ;
39 }
40 public void setAge(int age){
41 this.age = age ;
42 }
43 public String getName(){
44 return this.name;
45 }
46 public int getAge(){
47 return this.age ;
48 }
49 public String toString(){
50 return "学生姓名:" + this.name + ";年龄:" + this.age ;
51 }
52 }
53
54 //学校类
55 class School{
56 private String name ;
57 private List<Student> allStudents ;//一个学校有多个学生
58 public School(String name){
59 this.allStudents = new ArrayList<Student>();
60 this.setName(name) ;
61 }
62 public void setName(String name){
63 this.name = name ;
64 }
65 public String getName(){
66 return this.name;
67 }
68 public List<Student> getAllStudents(){//取得全部的学生
69 return this.allStudents ;
70 }
71 public String toString(){
72 return "学校名称:" + this.name ;
73 }
74 }
代码参考:https://www.cnblogs.com/xscn/archive/2013/08/09/3249274.html