top
Loading...
循速漸進學用SessionBean(五)
創建一個實用的Session Bean

HelloWorldSession例子的主要目的是幫助你熟悉一個session bean的整體結構。現在你已經熟悉了session bean的結構,你可以寫一個更實用的bean了。特別地,你可以寫一個由數據庫中接收數據的bean。

以下的例子,假定你擁有一個SQL表格,里面包含有產品的代碼和價格,你也可以使用以下SQL命令建立它:

create table price
(product_code varchar(10) not null primary key,
price decimal(10,2) not null)

Pricing session bean可以列出全部有效的產品代碼,并且可以返回某個產品代碼的價格,該代碼由Remote接口指定,如6.9列表所示:

Listing 6.9 Source Code for Pricing.java
package usingj2ee.pricing;

import java.rmi.*;
import javax.ejb.*;

/** Defines the methods you can call on a Pricing session */

public interface Pricing extends EJBObject
{

/** Returns all the available product codes */
public String[] getProductCodes() throws RemoteException;

/** Returns the price for a specific product code */
public double getPrice(String productCode)
throws RemoteException, InvalidProductCodeException;

}

Pricing session bean并不需要記得某個客戶的任何信息,所以可以用一個無狀態的session bean實現。PricingHome接口如列表6.10所示,它僅需要一個create方法。

Listing 6.10 Source Code for PricingHome.java
package usingj2ee.pricing;

import java.rmi.*;
import javax.ejb.*;

/** Defines the methods for creating a Pricing session */

public interface PricingHome extends EJBHome
{

/** Creates a Pricing session bean */
public Pricing create() throws RemoteException, CreateException;

}

當一個session bean需要訪問一個數據庫連接時,它通常在setSessionContext方法中分配一個連接,最后在ejbRemote方法中釋放它。當然,如果你擁有一個數據庫的連接,在容器調用ejbPassivate方法時,你必須準備關閉它,在容器調用ejbActivate時,重新得到連接。
作者:http://www.zhujiangroad.com
來源:http://www.zhujiangroad.com
北斗有巢氏 有巢氏北斗