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

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

刪除:

UCDeleteProduct類允許用於從products中選擇一條記錄並將它從庫中刪除。輸

入產品的productId,broker試著查詢指定的product。我們不需要擁有真個產品目錄,

所以查詢是很有必要的。Broker接著將找到的product刪除,程式碼如下:

public void apply()

{

  String in = readLineWithMessage("Delete Product with id:");

  int id = Integer.parseInt(in);

  // We do not have a reference to the ed Product.

  // So first we have to lookup the ,

  // we do this by a query by example (QBE):

  // 1. build an example object with matching primary key values:

  Product example = new Product();

  example.setId(id);

  // 2. build a QueryByCriteria from this sample instance:

  Query query = new QueryByCriteria(example);

  try

  {

  // start broker transaction

  broker.beginTransaction();

  // lookup the product specified by the QBE

  Product toBeDeleted = (Product) broker.getObjectByQuery(query);

  // now ask broker to delete the object

  broker.delete(toBeDeleted);

  // commit transaction

  broker.commitTransaction();

  }

  catch (Throwable t)

  {

  // rollback in case of errors

  broker.abortTransaction();

  t.printStackTrace();

  }

}

在本文中,QueryByCriteria方法被用來使功能實現變得簡單,程式碼更加少。我們也可以

透過Criteria物件建立一個指定過濾條件的查詢,下面的程式碼簡單地實現了透過Criter

ia物件來建立一個查詢:

// build filter criteria:

  Criteria criteria = new Criteria();

  criteria.addEqualTo(_id, new Integer(id));

  // build a query for the class Product with these filter criteria:

  Query query = new QueryByCriteria(Product.class, criteria);

...

我們可以任意地指定條件來建立複雜的查詢。下面的程式碼透過Criteria類實現了一個更

複雜查詢,它將獲得所有價格少於5。40,並且至少有兩百萬庫存量的產品目錄:

// build filter criteria:

  Criteria criteria = new Criteria();

  criteria.addLessThan("price", new Double( 5.40 ));

  criteria.addGreaterThan("stock", new Integer( 2000000 ));

  // build a query for the class Product with these filter criteria:

  Query query = new QueryByCriteria(Product.class, criteria);

...

完成例項:

例項程式的完成工作留給讀者自己。

現在你應該已經對OJB PesistenceBroker的基本功能很熟悉。為了更好的深入,你可以

考慮實現下面的額外功能:

1. 列出所有價格大於1000的產品目錄(或者讓使用者輸入條件)

2. 刪除所有庫存量為0的產品

3. 給所有價格低於500的產品提價11%(並存入儲存庫)


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

相關文章