tags:

views:

52

answers:

1

1.this is how my dao class look like where the transaction code keep repeat for every method. possible to put these snippet code in super class so that i do no need to repeat below code all the time? any elaborate how to do this?
2.if there is a need to put the snippet in super.class. should the super.class be static?

 for (int i = 0; i < NUM_RETRIES; i++) {
     pm.currentTransaction().begin();

     <all my code will be here>

     try {
         pm.currentTransaction().commit();
         break;

     } catch (JDOCanRetryException ex) {
         if (i == (NUM_RETRIES - 1)) { 
             throw ex;
         }
     }
 }
+1  A: 

Addressing only the "extract to superclass" issue, you could:

In your base class put:

public abstract Object doTransaction();

public abstract Object executeTransaction(some params){
for (int i = 0; i < NUM_RETRIES; i++) {
     pm.currentTransaction().begin();

     this.doTransaction();

     try {
         pm.currentTransaction().commit();
         break;

     } catch (JDOCanRetryException ex) {
         if (i == (NUM_RETRIES - 1)) { 
             throw ex;
         }
     }
 }
}

In your derived class, redefine doTransaction method

public Object doTransaction() {

 //access database and stuff;
}

Please adjust the return types and parameters accordingly.

Note that there's nothing static (static methods cant be overridden), its just an implementation of the template method pattern.

Tom
example in dao, i have method public List<String> getSomething(){ //how to call doTransaction of base class? }
cometta
if you need to explicitly call the getSOmething() method on your base class (from a derived instance), just do super.getSomething()
Tom
tom can explain more how i put this into dao. my dao extends base class?
cometta
from your example, it seem that i can only call doTraction() one time in the dao class
cometta
Yes, your dao extends a base class.
Tom
what i looking for is like below -- > class testDao extends BaseClass{ public List<String> getSomething(){ return doTEmplate.getSomething(); }; public void saveToDB(){ doTemplate.doSave(); } } //something similar to spring, but i interested to know how the backend work
cometta