This is an example of a "persistence framework" using an "inheritance"
hierarchy inconjunction with the Template Method Pattern.

Each persistable class is a subclass of an Abstract Base class that knows how to persist itself because it's SQL information is stored inside itself, and the Base class is responsible for executing that code by using a "template method".


public abstract class BaseObject
{
    public void commitTransaction(Connection pConn)
    {
        Statement stmt = pConn.createStatement();
        String query = getInsertSQLStatement(); // only defined in subclasses
        stmt.executeQuery(query);
    }

    private Connection getDBConnection()
    {
        // get DB connection
    }

    public abstract String getInsertSQLStatement();
    public abstract String getDeleteSQLStatement();
    public abstract String getUpdateSQLStatement();
}

public class MySessionBeanEJB implements SessionBean { public void commitTransaction(BaseObject pObject) { Connection conn = getDBConnection(); pObject.commitTransaction(conn); } private Connection getDBConnection() { // get DB connection }

public class Transaction extends BaseObject { private String name; private String address; private String city; public Transaction() { } public setName(String pName) { name = pName; } public setAddress(String pAddress) { address = pAddress; } public setCity(String pCity) { city = pCity; } public String getInsertSQLStatement() { return "INSERT INTO Company (" + name + "," + address + "," + city + ") VALUES(?,?,?)"; } public String getInsertSQLStatement() { return "UPDATE Company SET name = ? SET address = ? SET city = ? WHERE companyID = ?"; } public String getInsertSQLStatement() { return "DELETE FROM Company WHERE CompanyID = ? "; } }

public class JavaBean { public void processData(HttpRequest request, HttpResponse response) { String name = request.getParameter("name"); String address = request.getParameter("address"); String city = request.getParameter("city"); Transaction newTransaction = new Transaction(); newTransaction.setName(name); newTransaction.setAddress(address); newTransaction.setCity(city); Context myContext = getInitialContext(getContextFlag()); MySessionBeanHome home = myContext.lookup(pJNDIName); MySessionBeanRemote remoteEJB = home.create(); remoteEJB.commitTransaction(newTransaction); } }

Site hosted by Angelfire.com: Build your free website today!