軟件設(shè)計:EJB設(shè)計模式2

字號:

為了避免設(shè)計模式1的缺點,我們介紹一下封裝entity bean值域的value objec的概念。value object,用某些語言的術(shù)語來說,就是一個結(jié)構(gòu)類型,因為他們
    和corba的結(jié)構(gòu)類型非常類似。
    value Object code snippet for Company
    public class CompanyStruct implements
    java.io.Serializable {
    public Integer comId; //Primary Key
    public String comName;
    public String comDescription;
    public java.sql.Timestamp mutationDate;
    }
    value Object code snippet for Employee
    public class EmployeeStruct implements
    java.io.Serializable {
    public Integer empId; //Primary Key
    public Integer comId; //Foreign Key
    public String empFirstName;                                                                                                                                                             public String empLastName;
    public java.sql.Timestamp mutationDate;
    }
    現(xiàn)在,公司和雇員的entity bean可以把上面的一個結(jié)構(gòu)類型作為ejbCreate()的一個參數(shù)。由于這個結(jié)構(gòu)封裝了entity的所有字段的值,entity bean只需要一個getdata()和setdata()方法就可以對所有的字段進行操作。
    Code snippet for an Entity Bean’s create()
    public Integer ejbCreate(CompanyStruct struct) throws
    CreateException {
    this.comId = struct.comId;
    this.comName = struct.comName;
    this.comDescription = struct.comDescription;
    this.mutationDate = struct.mutationDate;
    return null;
    }
    Code snippet for an Entity Bean’s getData()
    public CompanyStruct getData() {
    CompanyStruct result = new CompanyStruct();
    result.comId = this.comId;
    result.comName = this.comName;
    result.comDescription = this.comDescription;                               result.mutationDate = this.mutationDate;
    return result;
    }
    Code snippet for an Entity Bean’s setData()
    public void setData(CompanyStruct struct) {
    this.comName = struct.comName;
    this.comDescription = struct.comDescription;
    this.mutationDate = struct.mutationDate;;
    }
    跟設(shè)計模式1中使用單獨的get()和set()方法去操作特定字段不同,在設(shè)計模式2中,我們避免這種情況而只需要進行一次遠程調(diào)用就可以了?,F(xiàn)在,只有一個事務(wù)通過一次遠程調(diào)用就操作了所有的數(shù)據(jù)。這樣,我們就避免了設(shè)計模式1的大部分缺點,除了建立bean之間的關(guān)系外。雖然setdata()方法可以對所有字段賦值,但是,borland appserver提供了一種智能更新的特性,只有被修改過的字段才會被重新寫入數(shù)據(jù)庫,如果沒有字段被修改,那么ejbStore()方法將會被跳過。borland程序員開發(fā)指南(EJB)有更詳細的描述。同樣,在entity bean和struct之間存在這重復(fù)的代碼,比如同樣的字段聲明。這意味著任何數(shù)據(jù)庫表結(jié)構(gòu)的修改都會導(dǎo)致entity beabn和struct的改變,這使得同步entity和struct變得困難起來。
    就是在ebCreate()方法中調(diào)用setddata()方法,這可以消除一些冗余的代碼。
    Code snippet for an Entity Bean’s create()
    public Integer ejbCreate(CompanyStruct struct) throws
    CreateException {
    this.comId = struct.comId; //set the primary key
    setData(struct);//this removes some redundant code
    return null;
    }