用OJB PersistenceBroker API实现各种功能:  
上面的一段代码很简单,因为没有涉及到存储操作,仅仅是程序的退出。下面让我们来  
看一个更具体的例子:UCListAllProducts类。该功能必须含有一个Collection类来包含  
数据库中的所有产品,然后将所有产品一一枚举并显示出来。为了得到数据库中的所有  
产品,我们需要使用OJB API中的一个方法。  
OJB提供三个主要的API:  
PersistenceBroker  
ODMG实现  
JDO实现  
在导学1中,我们使用PersistenceBroker API来实现所有的三个功能。导学2 D――使用  
ODMG API,导学4 D――使用JDO API将使用不同的数据库访问方法来实现同样的功能。  
   
你可以在org.apache.ojb.broker包中找到PersistenceBroker API的源码。该包中最关  
键的一个组件就是PersistenceBroker接口。他提供了获得对象,存储对象,删除对象的  
功能。在实际使用过程中,你需要获得一个Broker实例,配置相关的O/R映射关系,才能  
使用其提供的功能。  
获得一个Broker实例:  
怎样获得一个Broker实例?让我们来从Application类的构造函数中找答案:  
public Application()  
{  
    PersistenceBroker broker = null;  
    try  
    {  
        broker = PersistenceBrokerFactory.  
                    defaultPersistenceBroker();  
    }  
    catch (Throwable t)  
    {  
        t.printStackTrace();  
    }  
    useCases = new Vector();  
    useCases.add(new UCListAllProducts(broker));  
    useCases.add(new UCEnterNewProduct(broker));  
    useCases.add(new UCDeleteProduct(broker));  
    useCases.add(new UCQuitApplication(broker));  
}  
PersistenceBrokerFactory类使用./repositoty.xml作为映射仓库创建一个Pesistence  
Broker的实例,被创建的PesistenceBroker实例作为一个参数传到四个UseCase类的构造  
函数中去。  
获得Collections和Iterators:  
下面我们要做的就是用这个broker实例来进行存储操作。在这个功能中,我们需要从数  
据库中获得包含所有产品列表的collection。为了获得满足一些条件的collection,我  
们可以使用PersistenceBroker.getCollectionByQuery(Query query)方法。其中,Que  
ry是一个类,它提供特殊的条件如price>100或者userId=3.在我们的案例中,我们想要  
获得存储在Product表中的所有记录,所以我们不需要过滤条件。  
下面是UCListAllProducts.apply()方法的代码:  
public void apply()  
{  
    System.out.println("The list of available products:");  
    // build a query that selects all objects of Class Product,  
    // without any further criteria according to ODMG the  
    // Collection containing all instances of a  
    // persistent class is called "Extent"  
    Query query = new QueryByCriteria(Product.class, null);  
    try  
    {  
        // ask the broker to retrieve the Extent collection  
        Collection allProducts = broker.getCollectionByQuery(query);  
        // now iterate over the result to print each product  
        java.util.Iterator iter = allProducts.iterator();  
        while (iter.hasNext())  
        {  
  
            System.out.println(iter.next());  
        }  
    }  
    catch (Throwable t)  
    {  
        t.printStackTrace();  
    }  
}   
 
  |