KickJava   Java API By Example, From Geeks To Geeks.

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


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.PersistenceBrokerException;
20
21 /**
22  * Use case for adding a new product to the database.
23  */

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

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

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

49     public void apply()
50     {
51         // this will be our new object
52
Product newProduct = new Product();
53
54         // now read in all relevant information and fill the new object:
55
System.out.println("please enter a new product");
56
57         String JavaDoc in = readLineWithMessage("enter name:");
58
59         newProduct.setName(in);
60         in = readLineWithMessage("enter price:");
61         newProduct.setPrice(Double.parseDouble(in));
62         in = readLineWithMessage("enter available stock:");
63         newProduct.setStock(Integer.parseInt(in));
64
65         // now perform persistence operations
66
try
67         {
68             // 1. open transaction
69
broker.beginTransaction();
70
71             // 2. make the new object persistent
72
broker.store(newProduct);
73             broker.commitTransaction();
74         }
75         catch (PersistenceBrokerException ex)
76         {
77             // if something went wrong: rollback
78
broker.abortTransaction();
79             System.out.println(ex.getMessage());
80             ex.printStackTrace();
81         }
82     }
83 }
84
Popular Tags