KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > ojb > tutorial1 > UCDeleteProduct


1 package org.apache.ojb.tutorial1;
2
3 /* Copyright 2002-2004 The Apache Software Foundation
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17
18 import org.apache.ojb.broker.PersistenceBroker;
19 import org.apache.ojb.broker.query.Query;
20 import org.apache.ojb.broker.query.QueryByIdentity;
21
22 /**
23  * Use case for deleting a product from the database.
24  */

25 public class UCDeleteProduct extends AbstractUseCase
26 {
27     /**
28      * Creates a new delete use case instance.
29      *
30      * @param broker The broker to use for database operations
31      */

32     public UCDeleteProduct(PersistenceBroker broker)
33     {
34         super(broker);
35     }
36
37     /**
38      * Returns a description of this use case.
39      *
40      * @return A description of the use case
41      */

42     public String JavaDoc getDescription()
43     {
44         return "Delete a product entry";
45     }
46
47     /**
48      * Performs this use case.
49      */

50     public void apply()
51     {
52         String JavaDoc in = readLineWithMessage("Delete Product with id:");
53         int id = Integer.parseInt(in);
54
55         // We don't have a reference to the selected Product.
56
// So first we have to lookup the object,
57
// we do this by a query by example (QBE):
58

59         // 1. build an example object with matching primary key values:
60
Product example = new Product();
61
62         example.setId(id);
63
64         // 2. build a QueryByIdentity from this sample instance:
65
Query query = new QueryByIdentity(example);
66
67         try
68         {
69             // start broker transaction
70
broker.beginTransaction();
71             // lookup the product specified by the QBE
72
Product toBeDeleted = (Product) broker.getObjectByQuery(query);
73             // now ask broker to delete the object
74
broker.delete(toBeDeleted);
75             // commit transaction
76
broker.commitTransaction();
77         }
78         catch (Throwable JavaDoc t)
79         {
80             // rollback in case of errors
81
broker.abortTransaction();
82             t.printStackTrace();
83         }
84     }
85 }
86
Popular Tags