循速渐进学用Session Bean(五)

http://tech.ddvip.com   2006年11月24日    社区交流

本文详细介绍循速渐进学用Session Bean(五)

  创建一个实用的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时,重新得到连接。

责编:豆豆技术应用

正在加载评论...