为了避免设计模式1的缺点,我们介绍一下封装entity bean值域的value objec的概念。value object,用某些语言的术语来说,就是一个结构类型,因为他们和corba的结构类型非常类似。
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;
}
现在,公司和雇员的entity bean可以把上面的一个结构类型作为ejbcreate()的一个参数。由于这个结构封装了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;;
}
跟设计模式1中使用单独的get()和set()方法去操作特定字段不同,在设计模式2中,我们避免这种情况而只需要进行一次远程调用就可以了。现在,只有一个事务通过一次远程调用就操作了所有的数据。这样,我们就避免了设计模式1的大部分缺点,除了建立bean之间的关系外。
虽然setdata()方法可以对所有字段赋值,但是,borland appserver提供了一种智能更新的特性,只有被修改过的字段才会被重新写入数据库,如果没有字段被修改,那么ejbstore()方法将会被跳过。borland程序员开发指南(ejb)有更详细的描述。
同样,在entity bean和struct之间存在这重复的代码,比如同样的字段声明。这意味着任何数据库表结构的修改都会导致entity beabn和struct的改变,这使得同步entity和struct变得困难起来。
就是在ebcreate()方法中调用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;
}
闽公网安备 35060202000074号