Hibernate對映(七)— 元件
情況:
多個類中存在一些相同屬性,將其抽取出來
與繼承區別?
繼承:
繼承實在編譯時刻靜態定義的,較方便複用。但繼承對子類暴露了其父類的實現細節,破壞了封裝性;子類與父類有著較強的依賴關係,最終限制了複用
組合:
組合是通過獲得對其他物件的引用而在執行時刻動態定義的。基於介面進行開發,所以實現上依賴性小
設計模式第二原則:
少用繼承,多用組合
關係圖:
具體實現
1、實體
contact:
/**
* 共有的聯絡方式值類
* @author gxq
*
*/
public class Contact {
//定義郵箱、地址、郵箱編號、聯絡方式
private String email;
private String address;
private String zipCode;
private String contactTel;
public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getContactTel() { return contactTel; } public void setContactTel(String contactTel) { this.contactTel = contactTel; } }
User:
/**
* 定義使用者實體
* @author gxq
*
*/
public class User {
//id、姓名、聯絡方式
private int id;
private String name; private Contact userContact; public Contact getUserContact() { return userContact; } public void setUserContact(Contact userContact) { this.userContact = userContact; } 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; } }
Employee:
/**
* 定以員工實體
* @author gxq
*
*/
public class Employee {
//id、姓名、聯絡方式
private int id;
private String name;
private Contact employeeContact;
public Contact getEmployeeContact() {
return employeeContact;
}
public void setEmployeeContact(Contact employeeContact) {
this.employeeContact = employeeContact;
}
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;
}
}
2、對映檔案
User:
<component name="userContact">
<property name="email"></property>
<property name="address"></property>
<property name="zipCode"></property>
<property name="contactTel"></property>
</component>
</class>
</hibernate-mapping>
Employee:
<component name="employeeContact">
<property name="email"></property>
<property name="address"></property>
<property name="zipCode"></property>
<property name="contactTel"></property>
</component>
</class>
</hibernate-mapping>
3、配置檔案
com.mysql.jdbc.Driver