技术开发 频道

JAVA技术提升EJB性能的方法(下)


代码段2. 一个更好的方法

这里我们对代码段1所展示的接口进行改进。只不过这些接口方法一次可以传递更多的数据。
 
public interface Person extends EJBObject
 
{
 
public PersonData getPersonData()
 
throws RemoteException;
 
public void setPersonData(
 
PersonData personData)
 
throws RemoteException;
 
}
 
/* 这是一个value对象. value对象可以取得 细线优化的方法*/
 
public class PersonData implements Serializable
 
{
 
PersonData(String firstName, String lastName,
 
int personId)
 
{
 
this. firstName = firstName;
 
this. lastName = lastName;
 
this. personId = personId;
 
}
 
public String getFirstName() {
 
return firstName ; }
 
public String getLastName() {
 
return lastName; }
 
public int getPersonId(){ return personId; }
 
private String firstName;
 
private String lastName;
 
private int personId;
 
}
 
代码段3. 建立一个Facade
 
服务器端的facade为多个对象提供统一的接口。在这个例子中,ServerFacade为程序要用到的所有EJB的home handle提供缓存。
 
/* ServerFacade 为服务端的EJB 提供一个统一的接口。
 
所有客户端的类都通过ServerFacade访问服务器
 
*/
 
public class ServerFacadeBean implements SessionBean
 
{
 
file://缓存所有需要的EJB的home handle.
 
/* Person EJB 的home handle*/
 
PersonHome personHome = null;
 
/* Bank EJB的home handle*/
 
BankHome bankHome = null;
 
...
 
public ServerFacadeBean()
 
{
 
initialize();
 
}
 
public void initialize()
 
{
 
try
 
{ /* 初始化所有的Home handle.
 
We could also do lazy initialization
 
i.e., initialize as And when a home
 
handle is needed.
 
/* get initial context */
 
Context ctx = ...
 
if ( personHome == null )
 
personHome = (PersonHome)
 
ctx.lookup(PersonHome);
 
if ( bankHome == null )
 
bankHome = ( BankHome)
 
ctx.lookup(BankHome);
 
}
 
catch(Exception e)
 
{
 
/* 异常:查找失败*/
 
}
 
}
 
public PersonData getPersonData(int personId)
 
throws RemoteException
 
{
 
/*使用personHome缓存的副本*/
 
try
 
{
 
Person person = personHome.findByPrimaryKey(personId);
 
return person.getPersonData();
 
}
 
catch(Exception e)
 
{
 
/*异常处理*/
 
}
 
}
 
public BankData getBankData(int bankId)
 
throws RemoteException
 
{
 
/* 使用bankHome handle 缓存的副本*/
 
try
 
{
 
Bank bank =bankHome.findByPrimaryKey(bankId);
 
return bank.getBankData();
 
}
 
catch(Exception e)
 
{
 
/*异常处理*/
 
}
 
}
 
...
 
 
代码段4.一个调用
 
为了避免一次远程调用返回数据库的一行,可以用会话EJB对象将所有的数据打包成单个调用。
 
public class ServerFacadeBean implements SessionBean
 
{
 
...
 
>// 将行向量返回给客户端
 
public Vector findPersonsWithFirstName(
 
String firstName) throws RemoteException
 
{
 
Vector vector = new Vector();
 
Enumeration enumeration = null;
 
try
 
{
 
enumeration = personHome.findPersonsWithFirstName (firstName);
 
PersonData personData = null;
 
if ( enumeration != null )
 
{
 
while ( enumeration.hasMoreElements() )
 
{
 
Person person = (Person)enumeration.nextElement();
 
personData = person.getPersonData();
 
vector.addElement(personData);
 
}
 
}
 
}
 
catch(Exception e)
 
{
 
>/* 异常处理 */
 
}
 
return vector;
 
} ...
 
}
0
相关文章