在應用程式中將OJB作為一個儲存層使用(二) (轉)

gugu99發表於2007-08-17
在應用程式中將OJB作為一個儲存層使用(二) (轉)[@more@]

用OJB PersistenceBroker 實現各種功能:

上面的一段程式碼很簡單,因為沒有涉及到操作,僅僅是的退出。下面讓我們來

看一個更具體的例子:UCListAllProducts類。該功能必須含有一個Collection類來包含

中的所有產品,然後將所有產品一一列舉並顯示出來。為了得到資料庫中的所有

產品,我們需要使用OJB API中的一個方法。

OJB提供三個主要的API:

PersistenceBroker

ODMG實現

JDO實現

在導學1中,我們使用PersistenceBroker API來實現所有的三個功能。導學2 D――使用

ODMG API,導學4 D――使用JDO API將使用不同的資料庫訪問方法來實現同樣的功能。

 

你可以在org..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.作為對映倉庫建立一個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 s all s 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

  .util.Iterator iter = allProducts.iterator();

  while (iter.hasNext())

  {

 

  System.out.println(iter.next());

  }

  }

  catch (Throwable t)

  {

  t.printStackTrace();

  }

}


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10748419/viewspace-963447/,如需轉載,請註明出處,否則將追究法律責任。

相關文章