Pattern template

Can I learn how to create a child class if my childClass getInfoFromDB () method and saveToDB () must execute different logic?

public abstract class BaseClass {
    public abstract Object doTransaction();
    public Object executeTrans() {
          //do something
          tx.begin();            
          this.doTransaction();
          tx.commit();

    }
}
public childClass extends BaseClass{
    @Override
    public Object doTransaction(){
        //overide to get something from database so can only be used for getInfoFromDB() and not for saveToDB()
        return something;
    }
    public List<String> getInfoFromDB(){
        super.executeTrans();
    }
    public void saveToDB(){
        super.executeTrans() ;
    }
}
+3
source share
3 answers

In this case, you should use a template template, for example:

public abstract class BaseClass 
{      
  public Object executeTrans(Template template) 
  {
    tx.begin();            
    template.doTransaction();
    tx.commit();    
  }
}

public interface Template
{
  public void doTransaction();
}

public childClass extends BaseClass
{
  public List<String> getInfoFromDB()
  {
    executeTrans(
      new Template()
      {
        public void doTransaction() 
        {
          ...do get info from DB here.
        }
      }
    );
  }

  public void saveToDB()
  {
    executeTrans(
      new Template()
      {
        public void doTransaction() 
        {
          ...do save to DB here.
        }
      }
    );
  }
}

Speaking of this, I would advise using the Spring JDBC template classes instead of riding on their own - they have been tried and tested and solved the problems you encountered with nested transactions, etc.

+4
source

Pass a Runnable containing different logic to the executeTrans () method.

, ( ?). , , ​​ Spring, .

+1

Nick, the “tx” I'm going to use, looks below. judging by the code, the best practice is the life cycle, as it is called both savetodb () and getinfofromdb ()

public abstract class BaseClass 
{      
  public Object executeTrans(Template template) 
  {
        // PersistenceManager pm = ...;
        Transaction tx = pm.currentTransaction();
        try {
            tx.begin();
             template.doTransaction();
            tx.commit();
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
        }

  }
}
+1
source

Source: https://habr.com/ru/post/1715155/


All Articles