删除对象:
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 selected Product.
// So first we have to lookup the object,
// 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%(并存入存储库)