KickJava   Java API By Example, From Geeks To Geeks.

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


1 package org.apache.ojb.tutorial2;
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 java.util.List JavaDoc;
19
20 import org.odmg.Implementation;
21 import org.odmg.Database;
22 import org.odmg.Transaction;
23 import org.odmg.OQLQuery;
24
25 /**
26  * Use case for deleting a product from the database.
27  */

28 public class UCDeleteProduct extends AbstractUseCase
29 {
30     /**
31      * Creates a new delete use case instance.
32      *
33      * @param odmg The odmg implementation to use
34      */

35     public UCDeleteProduct(Implementation odmg)
36     {
37         super(odmg);
38     }
39
40     /**
41      * Returns a description of this use case.
42      *
43      * @return A description of the use case
44      */

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

53     public void apply()
54     {
55         String JavaDoc in = readLineWithMessage("Delete Product with id:");
56         int id = Integer.parseInt(in);
57
58         // We don't have a reference to the selected Product.
59
// So first we have to lookup the object.
60

61         // 1. build oql query to select product by id:
62
String JavaDoc oqlQuery = "select del from " + Product.class.getName() + " where id = " + id;
63
64         Database db = odmg.getDatabase(null); // the current DB
65
Transaction tx = null;
66
67         try
68         {
69             // 2. start transaction
70
tx = odmg.newTransaction();
71             tx.begin();
72
73             // 3. lookup the product specified by query
74
OQLQuery query = odmg.newOQLQuery();
75
76             query.create(oqlQuery);
77
78             List JavaDoc result = (List JavaDoc)query.execute();
79             Product toBeDeleted = (Product)result.get(0);
80
81             // 4. now mark object for deletion
82
db.deletePersistent(toBeDeleted);
83             // 5. commit transaction
84
tx.commit();
85         }
86         catch (Throwable JavaDoc t)
87         {
88             // rollback in case of errors
89
tx.abort();
90             t.printStackTrace();
91         }
92     }
93 }
94
Popular Tags