可以想像成一些學生會住在宿舍的同一間房間,
或是一間公司中,會有好幾個員工有同一個上司等等了。
那我還是以上一篇的多對一例子的資料表來實做多對一的關係映射
思考一下多對一的關係,即是很多個學生認得一間寢室
所以在學生 (Student) 類別裡,就必須引用所屬的寢室(Room)
程式如下:
package MapPOJO; public class Student implements java.io.Serializable { private Long id; private String name; private Room room; //引用(reference) Room public Student(){} public Long getId(){ return id; } public void setId(Long id){ this.id = id; } public String getName(){ return name; } public void setName(String name){ this.name = name; } public room getRoom() { return room; } public void setRoom(room room) { this.room = room; } }
package MapPOJO; public class Room implements java.io.Serializable { private Long id; private String address; //這邊 Room 並沒有引用 Student, 即 Room 不認得 Student public Room(){} public Long getId(){ return id; } public void setId(Long id){ this.id = id; } public String getAddress(){ return address; } public void setAddress(String address){ this.address = address; } }
完成好對應的類別後,再來看看映射文件如何將物件映射置資料庫
Room.hbm.xml
Student.hbm.xml
以上是 Room 和 Student 的映射文件
到目前為止相信應該都還不難理解
最後要記得在配置文件 hibernate.cfg.xml 中加入以下
<mapping resource="MapPOJO/Student.hbm.xml"/>
<mapping resource="MapPOJO/Room.hbm.xml"/>
接下來一樣透過一張 JSP 對資料庫進行儲存
// JSP 省略部份..... Room room1 = new Room(); Room room2 = new Room(); room1.setAddress("ABCD"); room2.setAddress("EFGH"); Student student1 = new Student(); Student student2 = new Student(); Student student3 = new Student(); student1.setName("ALLEN"); student1.setRoom(room1); student2.setName("Bob"); student2.setRoom(room1); student3.setName("Candy"); student3.setRoom(room2); org.hibernate.SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); org.hibernate.Session sess = sessionFactory.openSession(); Transaction tx = sess.beginTransaction(); sess.save(student1); sess.save(student2); sess.save(student3); tx.commit(); sess.close(); // JSP 省略部份.....
沒有留言:
張貼留言