Hibernate学习笔记_关系映射_学生_课程_分数
1 学生课程、分数的设计(重要)
@Entity public class Student { private int id; private String name; private Set<Course> courses = new HashSet<Course>(); @ManyToMany @JoinTable(name="score", joinColumns=@JoinColumn(name="student_id"), inverseJoinColumns=@JoinColumn(name="course_id") ) public Set<Course> getCourses() { return courses; } public void setCourses(Set<Course> courses) { this.courses = courses; } @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
@Entity public class Course { private int id; private String name; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
@Entity @Table(name="score") public class Score { private int id; private int score; private Student student; private Course course; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } @ManyToOne @JoinColumn(name="student_id") public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } @ManyToOne @JoinColumn(name="course_id") public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } }
@Test public void testSave() { Student s = new Student(); s.setName("zhangsan"); Course c = new Course(); c.setName("java"); Score score = new Score(); score.setCourse(c); score.setStudent(s); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(s); session.save(c); session.save(score); session.getTransaction().commit(); session.close(); } @Test public void testLoad() { testSave(); Session session = sessionFactory.openSession(); session.beginTransaction(); Student s = (Student)session.load(Student.class, 1); for(Course c : s.getCourses()) { System.out.println(c.getName()); } session.getTransaction().commit(); session.close(); }