Use OJB as a storage layer in the application (4)

zhaozj2021-02-12  177

Delete objects:

The UcdeleteProduct class allows you to select a record from Products and remove it from the repository. User lose

Enter the product's ProductID, Broker tries to find the specified product. We don't need to have a true product catalog,

So finding it is necessary. Broker then deletes the found product, the code is as follows:

Public void apply ()

{

String in = ReadlineWithMessage ("Delete Product with ID:");

INT ID = integer.parseint (in);

// We do Not Have a reference to the successd 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 tobedeted = (product) Broker.getObjectByQuery (Query);

// now ask Broker to delete the object

Broker.delete (TobeDeled);

// Commit Transaction

Broker.committransaction ();

}

Catch (throwable t)

{

// rollback in case of errors

Broker.aborttransaction ();

T.PrintStackTrace ();

}

}

In this article, the QueryByCriteria method is used to make the function implementation simple, and the code is less. We can also

Create a query specified by the Criteria object, the following code simply implements through crriter

Ia object to create a query:

// 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);

...

We can arbitrarily specify conditions to create complex queries. The following code achieves a more than the Criteria class.

Complex query, it will get all the price less than 5.40, and at least two million inventory of the product catalog:

// 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);

...

Complete the example program:

The completion of the instance program is left to the reader himself.

Now you should have been familiar with the basic functions of OJB PesistenceBroker. For better deepening, you can

Consider achieving the following additional functions:

1. List all prices of more than 1000 catalog (or let user input conditions)

2. Remove all stocks 0 products

3. Take a price of all products below 500 (and stored in a repository)

转载请注明原文地址:https://www.9cbs.com/read-6256.html

New Post(0)