以值型別的定義,一個物件中如果沒有一個能識別物件的屬性且對應到資料庫的主鍵的話通常稱為值型別
而在一對多的例子當中,實際上並沒有 Email 這個類別,如果有需求才會建立該類別
譬如你需要記住每個 email 的長度、密碼、種類....等,這時候的確可以建立一個 Email 類別
class Email{
private String emailName;
private String password;
private int length;
private String emailType; //例如yahoo或是gmail hotmail 等
}
以上一篇的"一對多(Value Type)"為例,雖然 email 在資料庫中有相對應的資料表
但剛剛 Email 類別中並無任何一個屬性對應資料庫的主鍵,
這時候要如何將 Email 物件的屬性資料映射到資料庫中就要利用 Component
這邊我以 Employee 和 Photo 為範例
看一下 ER Diagram :
一個員工會有多張的照片,屬於一對多,這邊特定建立 Photo 類別
來存放更多有關照片的資訊,例如:長與寬。看一下以下類別
Employee.java
package MapPOJO; import java.util.Set; public class Employee implements java.io.Serializable { private Long id; private String name; private SetPhoto.javaphotos; //一個Employee 對應到多個Photo public EmployeeOne(){} 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 Set getPhotos(){ return photos; } public void setPhotos(Set photos){ this.photos = photos; } }
package MapPOJO; public class Photo implements java.io.Serializable { //Photo 並沒有任何一個屬性對應到資料庫的主鍵, 屬於值型別 private String photoFileName; private int width; private int height; public PhotoOne(){} public String getPhotoFileName(){ return photoFileName; } public void setPhotoFileName(String photoFileName){ this.photoFileName = photoFileName; } public int getWidth(){ return width; } public void setWidth(int width){ this.width = width; } public int getHeight(){ return height; } public void setHeight(int height){ this.height = height; } }
看一下 Employee 的組態檔
Employee.hbm.xml
以下以 JSP 模擬 INSERT 資料
//省略 部份HTML....
<%
EmployeeOne e1 = new EmployeeOne();
EmployeeOne e2 = new EmployeeOne();
e1.setName("Allen1");
e2.setName("Tom2");
PhotoOne p1 = new PhotoOne();
PhotoOne p2 = new PhotoOne();
PhotoOne p3 = new PhotoOne();
PhotoOne p4 = new PhotoOne();
PhotoOne p5 = new PhotoOne();
p1.setPhotoFileName("C://company/Employee/Allen/P1");
p1.setHeight(100);
p1.setWidth(100);
p2.setPhotoFileName("C://company/Employee/Allen/P2");
p2.setHeight(200);
p2.setWidth(200);
p3.setPhotoFileName("C://company/Employee/Tom/P1");
p3.setHeight(100);
p3.setWidth(100);
p4.setPhotoFileName("C://company/Employee/Tom/P2");
p4.setHeight(200);
p4.setWidth(200);
p5.setPhotoFileName("C://company/Employee/Tom/P3");
p5.setHeight(300);
p5.setWidth(300);
Set
Set
photos1.add(p1);photos1.add(p2);
photos2.add(p3);photos2.add(p4);photos2.add(p5);
e1.setPhotos(photos1);
e2.setPhotos(photos2);
org.hibernate.SessionFactory sessionfactory = HibernateUtil.getSessionFactory();
org.hibernate.Session sess = sessionfactory.openSession();
org.hibernate.Transaction tx = sess.beginTransaction();
sess.save(e1);
sess.save(e2);
tx.commit();
sess.close();
%>
沒有留言:
張貼留言