You are viewing a plain text version of this content. The canonical link for it is here.
Posted to ojb-dev@db.apache.org by ar...@apache.org on 2004/02/25 02:12:41 UTC

cvs commit: db-ojb/src/test/org/apache/ojb/tutorials Product.java PBExample.java

arminw      2004/02/24 17:12:41

  Modified:    .        build.xml
               xdocs    pb-tutorial.xml
               src/test/org/apache/ojb/tutorials Product.java
                        PBExample.java
  Log:
  - minor changes in the PB tutorial
  always use tx-declaration on persistent operations
  
  Revision  Changes    Path
  1.114     +2 -1      db-ojb/build.xml
  
  Index: build.xml
  ===================================================================
  RCS file: /home/cvs/db-ojb/build.xml,v
  retrieving revision 1.113
  retrieving revision 1.114
  diff -u -r1.113 -r1.114
  --- build.xml	2 Feb 2004 10:31:22 -0000	1.113
  +++ build.xml	25 Feb 2004 01:12:41 -0000	1.114
  @@ -1209,6 +1209,7 @@
   	<copy file="${src.test}/org/apache/ojb/repository_internal.xml" tofile="${build.dir}/doc/repository_internal.xml.txt" />
   	<copy file="${src.test}/org/apache/ojb/repository_junit.xml" tofile="${build.dir}/doc/repository_junit.xml.txt" />
   	<copy file="${src.test}/org/apache/ojb/repository_user.xml" tofile="${build.dir}/doc/repository_user.xml.txt" />
  +	<copy file="${src.test}/org/apache/ojb/tutorials/PBExample.java" tofile="${build.dir}/doc/PBExamples.txt" />
   
   	<copy file="${src.test}/org/apache/ojb/OJB.properties" tofile="${build.dir}/doc/OJB.properties.txt" />
     </target>
  
  
  
  1.4       +139 -111  db-ojb/xdocs/pb-tutorial.xml
  
  Index: pb-tutorial.xml
  ===================================================================
  RCS file: /home/cvs/db-ojb/xdocs/pb-tutorial.xml,v
  retrieving revision 1.3
  retrieving revision 1.4
  diff -u -r1.3 -r1.4
  --- pb-tutorial.xml	7 Jan 2004 14:22:41 -0000	1.3
  +++ pb-tutorial.xml	25 Feb 2004 01:12:41 -0000	1.4
  @@ -46,31 +46,38 @@
                   </p>
                   <p>
                       The source code for this tutorial is available with the source distribution
  -                    of OJB in the <code>src/test/org/apache/ojb/tutorials/</code> directory.
  +                    of OJB in the <a href="PBExamples.txt"><code>src/test/org/apache/ojb/tutorials/</code></a> directory.
                   </p>
               </subsection>
               <subsection name="A First Look - Persisting New Objects">
                   <p>
                       The most basic operation is to persist an object. This is handled very easily
  -                    by just (1) obtaining a <code>PersistenceBroker</code>, (2) storing the object
  -                    via the <code>PersistenceBroker</code>, and (3) closing the
  -                    <code>PersistenceBroker</code>. For example, the following function stores
  +                    by just (1) obtaining a <code>PersistenceBroker</code>, (2) begin the PB-transaction,
  +                    (3) storing the object via the <code>PersistenceBroker</code>, (4) commit transaction and (5)
  +                    closing the <code>PersistenceBroker</code>. For example, the following function stores
                       a single object of type <code>Product</code>.
                   </p>
                   <source><![CDATA[
  -    public static void storeProduct(Product product)
  +public static void storeProduct(Product product)
  +{
  +    PersistenceBroker broker = null;
  +    try
       {
  -        PersistenceBroker broker = null;
  -        try
  -        {
  -            broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  -            broker.store(product);
  -        }
  -        finally
  -        {
  -            if (broker != null) broker.close();
  -        }
  +        broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  +        broker.beginTransaction();
  +        broker.store(product);
  +        broker.commitTransaction();
  +    }
  +    catch(PersistenceBrokerException e)
  +    {
  +        if(broker != null) broker.abortTransaction();
  +        // do more exception handling
  +    }
  +    finally
  +    {
  +        if (broker != null) broker.close();
       }
  +}
                   ]]></source>
                   <p>
                       Two OJB classes are used here, the <code>PersistenceBrokerFactory</code> and
  @@ -108,24 +115,29 @@
                       a transaction, as follows.
                   </p>
                   <source><![CDATA[
  -    public static void storeProducts(Product[] products)
  +public static void storeProducts(Product[] products)
  +{
  +    PersistenceBroker broker = null;
  +    try
       {
  -        PersistenceBroker broker = null;
  -        try
  +        broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  +        broker.beginTransaction();
  +        for (int i = 0; i < products.length; i++)
           {
  -            broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  -            broker.beginTransaction();
  -            for (int i = 0; i < products.length; i++)
  -            {
  -                broker.store(products[i]);
  -            }
  -            broker.commitTransaction();
  -        }
  -        finally
  -        {
  -            if (broker != null) broker.close();
  +            broker.store(products[i]);
           }
  +        broker.commitTransaction();
       }
  +    catch(PersistenceBrokerException e)
  +    {
  +        if(broker != null) broker.abortTransaction();
  +        // do more exception handling
  +    }
  +    finally
  +    {
  +        if (broker != null) broker.close();
  +    }
  +}
                   ]]></source>
                   <p>
                       This contrived example stores all of the passed Product instances within
  @@ -141,21 +153,22 @@
                       using a template object, or by using specific criteria.
                   </p>
                   <source><![CDATA[
  -    public static Product findByTemplate(Product template)
  +public static Product findByTemplate(Product template)
  +{
  +    PersistenceBroker broker = null;
  +    Product result = null;
  +    try
       {
  -        PersistenceBroker broker = null;
  -        try
  -        {
  -            broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  -            QueryByCriteria query = new QueryByCriteria(template);
  -            Product result = (Product) broker.getObjectByQuery(query);
  -            return result;
  -        }
  -        finally
  -        {
  -            if (broker != null) broker.close();
  -        }
  +        broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  +        QueryByCriteria query = new QueryByCriteria(template);
  +        result = (Product) broker.getObjectByQuery(query);
  +    }
  +    finally
  +    {
  +        if (broker != null) broker.close();
       }
  +    return result;
  +}
                   ]]></source>
                   <p>
                       This function finds a <code>Product</code> by building a query against a template
  @@ -190,27 +203,27 @@
                       by hand. The following function does this.
                   </p>
                   <source><![CDATA[
  -    public static Collection getExpensiveLowStockProducts()
  +public static Collection getExpensiveLowStockProducts()
  +{
  +    PersistenceBroker broker = null;
  +    Collection results = null;
  +    try
       {
  -        PersistenceBroker broker = null;
  -        try
  -        {
  -            broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  -
  -            Criteria criteria = new Criteria();
  -            criteria.addLessOrEqualThan("stock", new Integer(20));
  -            criteria.addGreaterOrEqualThan("price", new Double(100000.0));
  +        broker = PersistenceBrokerFactory.defaultPersistenceBroker();
   
  -            QueryByCriteria query = new QueryByCriteria(Product.class, criteria);
  -            Collection results = broker.getCollectionByQuery(query);
  +        Criteria criteria = new Criteria();
  +        criteria.addLessOrEqualThan("stock", new Integer(20));
  +        criteria.addGreaterOrEqualThan("price", new Double(100000.0));
   
  -            return results;
  -        }
  -        finally
  -        {
  -            if (broker != null) broker.close();
  -        }
  +        QueryByCriteria query = new QueryByCriteria(Product.class, criteria);
  +        results = broker.getCollectionByQuery(query);
  +    }
  +    finally
  +    {
  +        if (broker != null) broker.close();
       }
  +    return results;
  +}
                   ]]></source>
               <p>
                   This function builds a <code>Criteria</code> object and uses it to set more complex
  @@ -262,29 +275,38 @@
                       The following function demonstrates this behavior by "selling" a Product.
                   </p>
                   <source><![CDATA[
  -    public static boolean sellOneProduct(Product template)
  +public static boolean sellOneProduct(Product template)
  +{
  +    PersistenceBroker broker = null;
  +    boolean isSold = false;
  +    try
       {
  -        PersistenceBroker broker = null;
  -        try
  -        {
  -            broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  -            QueryByCriteria query = new QueryByCriteria(template);
  +        broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  +        QueryByCriteria query = new QueryByCriteria(template);
  +        Product result = (Product) broker.getObjectByQuery(query);
   
  +        if (result != null)
  +        {
               broker.beginTransaction();
  -            Product result = (Product) broker.getObjectByQuery(query);
  -            if (result == null) return false; // No product matched template
  -
               result.setStock(new Integer(result.getStock().intValue() - 1));
               broker.store(result);
  -
  +            // alternative, more performant
  +            // broker.store(result, ObjectModificationDefaultImpl.UPDATE);
               broker.commitTransaction();
  -            return true;
  -        }
  -        finally
  -        {
  -            if (broker != null) broker.close();
  +            isSold = true;
           }
       }
  +    catch(PersistenceBrokerException e)
  +    {
  +        if(broker != null) broker.abortTransaction();
  +        // do more exception handling
  +    }
  +    finally
  +    {
  +        if (broker != null) broker.close();
  +    }
  +    return isSold;
  +}
                   ]]></source>
               <p>
                   This function uses the same query-by-template and <code>PersistenceBroker.store()</code>
  @@ -300,19 +322,26 @@
                       on the object itself. For example:
                   </p>
                   <source><![CDATA[
  -    public static void deleteProduct(Product product)
  +public static void deleteProduct(Product product)
  +{
  +    PersistenceBroker broker = null;
  +    try
       {
  -        PersistenceBroker broker = null;
  -        try
  -        {
  -            broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  -            broker.delete(product);
  -        }
  -        finally
  -        {
  -            if (broker != null) broker.close();
  -        }
  +        broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  +        broker.beginTransaction();
  +        broker.delete(product);
  +        broker.commitTransaction();
       }
  +    catch(PersistenceBrokerException e)
  +    {
  +        if(broker != null) broker.abortTransaction();
  +        // do more exception handling
  +    }
  +    finally
  +    {
  +        if (broker != null) broker.close();
  +    }
  +}
                   ]]></source>
                   <p>
                       This method simply deletes an object from the database.
  @@ -345,9 +374,9 @@
                       <code>org.apache.ojb.broker.PersistenceBrokerException</code>, which is derived from
                       <code>java.lang.RuntimeException</code> if an error occurs. This means that no try/catch
                       block is <b>required</b> but does not mean that it should not be used. This tutorial
  -                    specifically does not catch exceptions in order to focus more tightly on the
  -                    specifics of the API, however, better usage would be to include a try/catch
  -                    around persistence operations using the PeristenceBroker API.
  +                    specifically does not catch exceptions all in order to focus more tightly on the
  +                    specifics of the API, however, best usage would be to include a try/catch/finally
  +                    block around persistence operations using the PeristenceBroker API.
                   </p>
                   <p>
                       Additionally, the closing of <code>PersistenceBroker</code> instances is best
  @@ -363,32 +392,31 @@
                       here.
                   </p>
                   <source><![CDATA[
  -    public static Collection betterGetExpensiveLowStockProducts()
  +public static Collection betterGetExpensiveLowStockProducts()
  +{
  +    PersistenceBroker broker = null;
  +    Collection results = null;
  +    try
       {
  -        PersistenceBroker broker = null;
  -        try
  -        {
  -            broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  +        broker = PersistenceBrokerFactory.defaultPersistenceBroker();
   
  -            Criteria criteria = new Criteria();
  -            criteria.addLessOrEqualThan("stock", new Integer(20));
  -            criteria.addGreaterOrEqualThan("price", new Double(100000.0));
  +        Criteria criteria = new Criteria();
  +        criteria.addLessOrEqualThan("stock", new Integer(20));
  +        criteria.addGreaterOrEqualThan("price", new Double(100000.0));
   
  -            QueryByCriteria query = new QueryByCriteria(Product.class, criteria);
  -            Collection results = broker.getCollectionByQuery(query);
  -
  -            return results;
  -        }
  -        catch (PersistenceBrokerException e)
  -        {
  -            // Handle exception
  -        }
  -        finally
  -        {
  -            if (broker != null) broker.close();
  -        }
  -        return null;
  +        QueryByCriteria query = new QueryByCriteria(Product.class, criteria);
  +        results = broker.getCollectionByQuery(query);
  +    }
  +    catch (PersistenceBrokerException e)
  +    {
  +        // Handle exception
  +    }
  +    finally
  +    {
  +        if (broker != null) broker.close();
       }
  +    return results;
  +}
                   ]]></source>
                   <p>
                       Notice first that the <code>PersistenceBroker</code> is retrieved and used
  
  
  
  1.3       +9 -1      db-ojb/src/test/org/apache/ojb/tutorials/Product.java
  
  Index: Product.java
  ===================================================================
  RCS file: /home/cvs/db-ojb/src/test/org/apache/ojb/tutorials/Product.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- Product.java	18 Sep 2003 02:32:17 -0000	1.2
  +++ Product.java	25 Feb 2004 01:12:41 -0000	1.3
  @@ -1,5 +1,8 @@
   package org.apache.ojb.tutorials;
   
  +import org.apache.commons.lang.builder.ToStringBuilder;
  +import org.apache.commons.lang.builder.ToStringStyle;
  +
   /**
    * represents product objects in the tutorial system
    *
  @@ -94,6 +97,11 @@
   
       public String toString()
       {
  -        return "[" + id + "] " + name + "\t\t\t price: " + price + "\t\t stock: " + stock;
  +        ToStringBuilder buf = new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE);
  +        buf.append("id", id);
  +        buf.append("name", name);
  +        buf.append("price", price);
  +        buf.append("stock", stock);
  +        return buf.toString();
       }
   }
  
  
  
  1.2       +85 -31    db-ojb/src/test/org/apache/ojb/tutorials/PBExample.java
  
  Index: PBExample.java
  ===================================================================
  RCS file: /home/cvs/db-ojb/src/test/org/apache/ojb/tutorials/PBExample.java,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- PBExample.java	19 Aug 2003 15:35:57 -0000	1.1
  +++ PBExample.java	25 Feb 2004 01:12:41 -0000	1.2
  @@ -1,12 +1,13 @@
   package org.apache.ojb.tutorials;
   
  +import java.util.Collection;
  +
   import org.apache.ojb.broker.PersistenceBroker;
  -import org.apache.ojb.broker.PersistenceBrokerFactory;
   import org.apache.ojb.broker.PersistenceBrokerException;
  -import org.apache.ojb.broker.query.QueryByCriteria;
  +import org.apache.ojb.broker.PersistenceBrokerFactory;
  +import org.apache.ojb.broker.util.ObjectModificationDefaultImpl;
   import org.apache.ojb.broker.query.Criteria;
  -
  -import java.util.Collection;
  +import org.apache.ojb.broker.query.QueryByCriteria;
   
   /**
    * PB-api usage examples.
  @@ -22,7 +23,14 @@
           try
           {
               broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  +            broker.beginTransaction();
               broker.store(product);
  +            broker.commitTransaction();
  +        }
  +        catch(PersistenceBrokerException e)
  +        {
  +            if(broker != null) broker.abortTransaction();
  +            // do more exception handling
           }
           finally
           {
  @@ -43,6 +51,11 @@
               }
               broker.commitTransaction();
           }
  +        catch(PersistenceBrokerException e)
  +        {
  +            if(broker != null) broker.abortTransaction();
  +            // do more exception handling
  +        }
           finally
           {
               if (broker != null) broker.close();
  @@ -52,22 +65,24 @@
       public static Product findByTemplate(Product template)
       {
           PersistenceBroker broker = null;
  +        Product result = null;
           try
           {
               broker = PersistenceBrokerFactory.defaultPersistenceBroker();
               QueryByCriteria query = new QueryByCriteria(template);
  -            Product result = (Product) broker.getObjectByQuery(query);
  -            return result;
  +            result = (Product) broker.getObjectByQuery(query);
           }
           finally
           {
               if (broker != null) broker.close();
           }
  +        return result;
       }
   
       public static Collection getExpensiveLowStockProducts()
       {
           PersistenceBroker broker = null;
  +        Collection results = null;
           try
           {
               broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  @@ -77,19 +92,19 @@
               criteria.addGreaterOrEqualThan("price", new Double(100000.0));
   
               QueryByCriteria query = new QueryByCriteria(Product.class, criteria);
  -            Collection results = broker.getCollectionByQuery(query);
  -
  -            return results;
  +            results = broker.getCollectionByQuery(query);
           }
           finally
           {
               if (broker != null) broker.close();
           }
  +        return results;
       }
   
       public static Collection betterGetExpensiveLowStockProducts()
       {
           PersistenceBroker broker = null;
  +        Collection results = null;
           try
           {
               broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  @@ -99,9 +114,7 @@
               criteria.addGreaterOrEqualThan("price", new Double(100000.0));
   
               QueryByCriteria query = new QueryByCriteria(Product.class, criteria);
  -            Collection results = broker.getCollectionByQuery(query);
  -
  -            return results;
  +            results = broker.getCollectionByQuery(query);
           }
           catch (PersistenceBrokerException e)
           {
  @@ -111,55 +124,70 @@
           {
               if (broker != null) broker.close();
           }
  -        return null;
  +        return results;
       }
   
       public static boolean sellOneProduct(Product template)
       {
           PersistenceBroker broker = null;
  +        boolean isSold = false;
           try
           {
               broker = PersistenceBrokerFactory.defaultPersistenceBroker();
               QueryByCriteria query = new QueryByCriteria(template);
  -
  -            broker.beginTransaction();
               Product result = (Product) broker.getObjectByQuery(query);
  -            if (result == null) return false; // No product matched template
  -
  -            result.setStock(new Integer(result.getStock().intValue() - 1));
  -            broker.store(result);
   
  -            broker.commitTransaction();
  -            return true;
  +            if (result != null)
  +            {
  +                broker.beginTransaction();
  +                result.setStock(new Integer(result.getStock().intValue() - 1));
  +                broker.store(result);
  +                // alternative, more performant
  +                // broker.store(result, ObjectModificationDefaultImpl.UPDATE);
  +                broker.commitTransaction();
  +                isSold = true;
  +            }
  +        }
  +        catch(PersistenceBrokerException e)
  +        {
  +            if(broker != null) broker.abortTransaction();
  +            // do more exception handling
           }
           finally
           {
               if (broker != null) broker.close();
           }
  +        return isSold;
       }
   
       public static boolean findAndDeleteProduct(Product template)
       {
           PersistenceBroker broker = null;
  +        boolean isDeleted = false;
           try
           {
               broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  -
               QueryByCriteria query = new QueryByCriteria(template);
  -
  -            broker.beginTransaction();
               Product result = (Product) broker.getObjectByQuery(query);
  -            if (result == null) return false; // No product matched template
   
  -            broker.delete(result);
  -
  -            broker.commitTransaction();
  -            return true;
  +            if (result != null)
  +            {
  +                broker.beginTransaction();
  +                broker.delete(result);
  +                broker.commitTransaction();
  +                isDeleted = true;
  +            }
  +        }
  +        catch(PersistenceBrokerException e)
  +        {
  +            if(broker != null) broker.abortTransaction();
  +            // do more exception handling
           }
           finally
           {
               if (broker != null) broker.close();
           }
  +        return isDeleted;
       }
   
       public static void deleteProduct(Product product)
  @@ -167,8 +195,15 @@
           PersistenceBroker broker = null;
           try
           {
  -            PersistenceBrokerFactory.defaultPersistenceBroker();
  +            broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  +            broker.beginTransaction();
               broker.delete(product);
  +            broker.commitTransaction();
  +        }
  +        catch(PersistenceBrokerException e)
  +        {
  +            if(broker != null) broker.abortTransaction();
  +            // do more exception handling
           }
           finally
           {
  @@ -182,12 +217,31 @@
           product.setName("Sprocket");
           product.setPrice(new Double(1.99));
           product.setStock(new Integer(10));
  +        System.out.println("1a. Store product: " + product);
           storeProduct(product);
  +        System.out.println("1b. Product stored: " + product);
  +        System.out.println();
   
           Product template = new Product();
           template.setName("Sprocket");
  +        System.out.println("2a. Find product by template, used template: " + template);
           Product aProduct = findByTemplate(template);
  +        System.out.println("2b. Found product: " + aProduct);
  +        System.out.println();
   
  +        System.out.println("3a. Sell one product, stock before was " + aProduct.getStock());
           sellOneProduct(template);
  +        aProduct = findByTemplate(template);
  +        System.out.println("3b. Product sold, current stock is " + aProduct.getStock());
  +        System.out.println();
  +
  +        System.out.println("4a. Delete a product object");
  +        deleteProduct(aProduct);
  +        System.out.println("4b. Product deleted");
  +        System.out.println("4c. Try to lookup deleted product");
  +        Product newProduct = findByTemplate(aProduct);
  +        System.out.println("4d. Found product: " + newProduct);
  +
  +        System.exit(0);
       }
   }
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: ojb-dev-unsubscribe@db.apache.org
For additional commands, e-mail: ojb-dev-help@db.apache.org