Migration problems: Enhydra5.0 to Enhydra5.1

Axel Wilhelm Berle <[email protected]> Fri, 3 Oct 2003 14:13:28 +0200 (CEST)
Newsgroups gmane.comp.java.enhydra.general
Message-ID <[email protected]>
Hi Vladimir,

well, in fact we are using only some parts of Enhydra.
For the presentation layer, we use Xmlc; for the data
layer we use the database manager. The app runs
directly on tomcat.

As for our configuration:

- Java 1.4.2
- Postgres
- we generate the xxxDO classes ourselves

He is how we use the database manager:

ConfigFile configFile = new ConfigFile(new
File(database_config_path));
Config config = configFile.getConfig();
m_databaseManager = new
StandardDatabaseManager(config);

The config-file is:

Databases = "oksolutions"
DefaultDatabase = "oksolutions"
DB.oksolutions.ClassType = "Standard"
DB.oksolutions.JdbcDriver = "org.postgresql.Driver"
DB.oksolutions.Connection.MaxPreparedStatements = 10
DB.oksolutions.Connection.Url =
"jdbc:postgresql://192.168.0.200/oksolutions"
DB.oksolutions.Connection.User = "oks"
DB.oksolutions.Connection.Password = "password"
DB.oksolutions.Connection.MaxPoolSize = 5
DB.oksolutions.Connection.AllocationTimeout = 10000
DB.oksolutions.Connection.Logging = false
DB.oksolutions.ObjectId.CacheSize = 20
DB.oksolutions.ObjectId.MinValue = 1000000
ObjectIdColumnName = "objectid"
VersionColumnName = "objectversion"

The xxxxDO's are created "by hand" as the following
example:

package oksolution.data.counter;

import
com.lutris.appserver.server.sql.StandardDatabaseManager;
import
com.lutris.appserver.server.sql.DatabaseManagerException;
import com.lutris.appserver.server.sql.DBConnection;
import com.lutris.appserver.server.sql.DBQuery;
import com.lutris.appserver.server.sql.ObjectId;
import
com.lutris.appserver.server.sql.ObjectIdException;
import oksolution.data.BasicDO;


public class CounterDO extends BasicDO {
   //
--------------------------------------------------------------------------
   public static final String NAME               =
"name";
   public static final String CREATION_DATE      =
"creation_date";
   public static final String DESCRIPTION        =
"description";
   public static final String NUM_VISITAS        =
"num_visitas";
  //
---------------------------------------------------------------------------
   private String    m_name;
   private Date      m_creationDate;
   private String    m_description;
   private int       m_numVisitas;
  //
---------------------------------------------------------------------------

   public CounterDO(String name,
                    String description)
           throws ObjectIdException,
DatabaseManagerException {
      super();
      setName(name);
      setCreationDate(new
Date(java.lang.System.currentTimeMillis()));
      setDescription(description);
      setNumVisitas(0);
   }

   // Construct person data object from the given
database info
   public CounterDO(ResultSet rs)
            throws SQLException, ObjectIdException {
      super(rs);
      setNewVersion(getVersion());
      setName(rs.getString(NAME));
      setCreationDate(rs.getDate(CREATION_DATE));
      setDescription(rs.getString(DESCRIPTION));
      setNumVisitas(rs.getInt(NUM_VISITAS));
      setDirty(false);
   }

   // Parameter names
   // ORDER IS IMPORTANT! (use same order as in
setData)
   private static String[] PARAMETER_NAMES =
      {NAME,
       CREATION_DATE,
       DESCRIPTION,
       NUM_VISITAS};

    // Set database parameters for this person data
object
    // ORDER IS IMPORTANT! (use same order as in
getParameters)
    protected int setParameters(PreparedStatement
stmt, int param)
            throws SQLException {
	param = setString(stmt, param, getName());
        param = setDate(stmt,param,
getCreationDate());
	param = setString(stmt, param, getDescription());
        param = setInt(stmt, param, getNumVisitas());
 	return param;
    }

    // Get database parameters names (columns in
table)
    // ORDER IS IMPORTANT! (use same order as in
setParameters)
    protected String[] getParameters() {
	return PARAMETER_NAMES;
    }

   // Get database table name
   protected String getTableName() {
      return getDBTableName();
   }

   // Get main database table name
   public static String getDBTableName() {
      return "counter";
   }


  // - get/set
-----------------------------------------------------------------

  public String getName() {
    return m_name;
  }

  public void setName(String name) {
     m_name = name;
     setDirty(true);
  }

  public Date getCreationDate() {
     return m_creationDate;
  }

  public void setCreationDate(Date creationDate) {
     m_creationDate = creationDate;
  }

  public String getDescription() {
    return m_description;
  }

  public void setDescription(String description) {
    m_description = description;
    setDirty(true);
  }

  public int getNumVisitas() {
    return m_numVisitas;
  }

  public void setNumVisitas(int numVisitas) {
    m_numVisitas = numVisitas;
    setDirty(true);
  }

}

We took the BasicDO from one of the examples
distributed with Enhydra 3.1:

package oksolution.data;

import com.lutris.appserver.server.*;
import com.lutris.appserver.server.sql.*;
import java.sql.*;
import java.math.BigDecimal;
import java.util.StringTokenizer;
import java.sql.Time;

import oksolution.business.DatabaseManager;

/**
 * Basic data object.  This could be rolled into
CloneableDO and CoreDO.
 * <P>
 * <UL>
 * <LI>Keeps track of whether or not the data object
is "dirty"
 * <LI>Keeps track of whether or not the database is
being updated for
 *     this data object
 * <LI>Only updates database if the data object is
dirty
 * <LI>Does not update database if another process is
doing an update
 * </UL>
 *
 * @author Kristen Pol
 * @since Enhydra2.0
 */

public abstract class BasicDO extends CloneableDO {

    // protected data members

    // Is this data object dirty?
    protected boolean isDirty = false;

    // Is the database entry for this data object
being updated?
    protected boolean isExecuting = false;

    // constructors

    // Construct data object from scratch
    public BasicDO()
            throws ObjectIdException,
DatabaseManagerException {
	super();
        StandardDatabaseManager dbManager = null;
        try {
           dbManager =
DatabaseManager.getDatabaseManager(null);
        }
        catch(Exception e) {}
	setOId(dbManager.allocateObjectId());
	setDirty(true);
    }


    // Construct data object from data in database
    public BasicDO(ResultSet rs)
            throws SQLException, ObjectIdException {
        super(rs);
        setNewVersion(getVersion());
        setDirty(false);
    }

    // public and protected methods

    // Clone this data object uniquely
    public synchronized Object cloneUnique()
	    throws DatabaseManagerException,
ObjectIdException {
        BasicDO basicDO = (BasicDO)
super.cloneUnique();
        basicDO.setNewVersion(0);
        basicDO.setDirty(true);
        return basicDO;
    }

    /* ---- SETTER/GETTER METHODS ---- */

    // Set dirty flag
    protected void setDirty(boolean isDirty) {
        this.isDirty = isDirty;
    }

    // Is this data object dirty?
    public boolean isDirty() {
        return this.isDirty;
    }

    // Set executing flag
    protected void setExecuting(boolean isExecuting) {
        this.isExecuting = isExecuting;
    }

    // Is an execute method being called?
    public boolean isExecuting() {
        return this.isExecuting;
    }

    /* ---- INSERT METHODS ---- */

    // Insert the data for this data object in the
database
    public PreparedStatement
getInsertStatement(DBConnection conn)
            throws SQLException {
        String sql = "insert into " + getTableName() +
" \n" +
            "values " + createQuestionMarks(2 +
getNumParams());
        PreparedStatement stmt =
conn.prepareStatement(sql);
        int param = 1;
        stmt.setBigDecimal(param++,
getOId().toBigDecimal());
        stmt.setInt(param++, getVersion());
	param = setParameters(stmt, param);
        return stmt;
    }

    // Insert data into database
    public synchronized void
executeInsert(DBConnection conn)
            throws SQLException {
        if (! isExecuting()) {
            super.executeInsert(conn);
            setExecuting(true);
        }
    }

    // What to do after insert is done
    public void finalizeInsert(boolean success) {
        boolean p = persistent;
        super.finalizeInsert(success);
        if (p == true) {
            persistent = true; // Bug fix for CoreDO!
(it overwrites persistent)
        }
	done(success);
    }

    /* ---- UPDATE METHODS ---- */

    // Update the data for this data object in the
database
    public PreparedStatement
getUpdateStatement(DBConnection conn)
            throws SQLException {
        String sql =
            "update " + getTableName() + " \n" +
            "set " +
            "objectversion = ?, " +
	    createUpdateSql() +
            " where objectid = ? and objectversion =
?"; // [email protected].
        PreparedStatement stmt =
conn.prepareStatement(sql);
        int param = 1;
        stmt.setInt(param++, getNewVersion());
	param = setParameters(stmt, param);
        stmt.setBigDecimal(param++,
getOId().toBigDecimal());
        stmt.setInt(param++, getVersion());
        return stmt;
    }

    // Update data in database
    public synchronized void
executeUpdate(DBConnection conn)
            throws SQLException {
        if (isDirty() && ! isExecuting()) {
            super.executeUpdate(conn);
            setExecuting(true);
        }
    }

    // What to do after update is done
    public void finalizeUpdate(boolean success) {
        super.finalizeUpdate(success);
	done(success);
    }

    /* ---- DELETE METHODS ---- */

    // Delete the data for this data object from the
database
    public PreparedStatement
getDeleteStatement(DBConnection conn)
            throws SQLException {
        String sql = "delete from " + getTableName() +
" where objectid = ?";
        PreparedStatement stmt =
conn.prepareStatement(sql);
        stmt.setBigDecimal(1,
getOId().toBigDecimal());
        return stmt;
    }

    // Delete data from database
    public void executeDelete(DBConnection conn)
            throws SQLException {
        if (isPersistent()) {
	    while (! isExecuting()) {
		super.executeDelete(conn);
		setExecuting(true);
	    }
        }
    }

    // What to do after delete is done
    public void finalizeDelete(boolean success) {
        super.finalizeDelete(success);
	done(success);
    }

    /* ---- HELPER METHODS ---- */

    // What is the name of the database table for this
data object?
    protected abstract String getTableName();

    // Sql string to use for updating the database
    protected abstract String[] getParameters();

    // Set data for the given prepared statement
    protected abstract int
setParameters(PreparedStatement stmt, int param)
	throws SQLException;

    // Sql string to use for updating the database
    protected String createUpdateSql() {
	String[] parameters = getParameters();
	String sql = "";
	if (parameters != null) {
	    int length = parameters.length;
	    for (int i = 0; i < length; i++) {
		sql += parameters[i] + "= ?";
		if (i < (length - 1)) {
		    sql += ",";
		}
	    }
	}
	return sql;
    }

    // Creates string like "(?,?,?)" with numberMarks
number of question marks
    protected String createQuestionMarks(int
numberMarks)
            throws SQLException {
	String sql = "(";
	for (int i = 0; i < numberMarks; i++) {
	    sql += "?";
	    if (i < (numberMarks - 1)) {
		sql += ",";
	    }
	}
	sql += ")";
	return sql;
    }

    // How many parameters does this data object have?
    protected int getNumParams() {
	String updateSql = createUpdateSql();
	StringTokenizer tokenizer = new
StringTokenizer(updateSql, "?");
	return tokenizer.countTokens();
    }

    // Set the Int in the statement
    protected int setInt(PreparedStatement stmt, int
param, int data)
	    throws SQLException {
        stmt.setInt(param++, data);
	return param;
    }

    // Set the string in the statement
    protected int setString(PreparedStatement stmt,
int param, String data)
	    throws SQLException {
	if (data != null) {
	    stmt.setString(param++, data);
	} else {
	    stmt.setNull(param++, Types.VARCHAR);
	}
	return param;
    }

    protected int setObjectId(PreparedStatement stmt,
int param, ObjectId oid)
	    throws SQLException {
	if (oid != null) {
	    stmt.setBigDecimal(param++, oid.toBigDecimal());
	} else {
	    stmt.setNull(param++, Types.VARCHAR);
	}
	return param;
    }


    protected int setBigDecimal(PreparedStatement
stmt, int param, BigDecimal data)
	    throws SQLException {
	if (data != null) {
	    stmt.setBigDecimal(param++, data);
	} else {
	    stmt.setNull(param++, Types.VARCHAR);
	}
	return param;
    }

    protected int setDate(PreparedStatement stmt, int
param, Date data)
	    throws SQLException {
	if (data != null) {
	    stmt.setDate(param++, data);
	} else {
	    stmt.setNull(param++, Types.VARCHAR);
	}
	return param;
    }

    protected int setTimestamp(PreparedStatement stmt,
int param, Timestamp timestamp)
	    throws SQLException {
	if (timestamp != null) {
	    stmt.setTimestamp(param++, timestamp);
	} else {
	    stmt.setNull(param++, Types.VARCHAR);
	}
	return param;
    }

    protected int setTime(PreparedStatement stmt, int
param, Time data)
	    throws SQLException {
	if (data != null) {
	    stmt.setTime(param++, data);
	} else {
	    stmt.setNull(param++, Types.VARCHAR);
	}
	return param;
    }

    // Set the Long in the statement
    protected int setLong(PreparedStatement stmt, int
param, long data)
	    throws SQLException {
        stmt.setLong(param++, data);
	return param;
    }


    // private methods

    private void done(boolean success) {
	setDirty(! success);
	setExecuting(false);
    }
}



We make queries and transactions like that (inspired
by the examples distributed with Enhydra3.1):


  static public Vector getCounters() throws Exception
{
     // Pesquisar de novo, ordenado por NOME
     DBQuery db = null;
     Vector counterList = new Vector();
     try {
        CounterQuery counterQuery = new
CounterQuery();
        db = m_databaseManager.createQuery();
        db.query(counterQuery);
        CounterDO counterDO = null;
        while ((counterDO = (CounterDO) db.next()) !=
null) {
           counterList.addElement(counterDO);
        }
     } catch (Exception e) {
        throw e;
     } finally {
        db.release();
     }
     return counterList;
  }

or:

  public synchronized static void saveCounters()
throws Exception {
     // Write the counterDOs back to the database
     System.out.println("CounterManager: saving
counters...");
     DBTransaction db = null;
     try {
        db = m_databaseManager.createTransaction();
        Enumeration e = m_counterTable.keys();   //
counterName (string) -> CounterDO
        while (e.hasMoreElements()) {
           String counterName =
(String)e.nextElement();
           CounterDO counterDO =
(CounterDO)m_counterTable.get(counterName);
           db.update(counterDO);
        }
        db.commit();
     } catch (Exception e) {
        System.out.println("ERROR:
CounterManager.saveCounters(): " + e.getMessage());
        e.printStackTrace(System.out);
        db.rollback();
     } finally {
        db.release();
     }
  }


I think this wraps it all up. We hope you can give us
some pointers. Thanks in advance for the help,

Axel





=====
Axel Wilhelm Berle

e-mail: [email protected]
Tel: (office) +55 16 618.0090
     (mobile) +55 16 9964.6343

__________________________________________________________________

Gesendet von Yahoo! Mail - http://mail.yahoo.de
Logos und Klingeltöne fürs Handy bei http://sms.yahoo.de