Hi all,

Noticing that PlatformImplBase.store() was not implemented, I'd
propose and discuss an implementation for it (attached).

To be discussed:
1) I think I need the Database model for the getDynaClassFor call, but
in order to acommodate that I changed
protected boolean exists(Connection connection, DynaBean dynaBean)
to
protected boolean exists(Connection connection, Database model,
DynaBean dynaBean)
What were the thoughts behind the original method signature choice?

2) I'm not sure about exception that should be thrown if exists fails,
currently:
catch (SQLException ex)
{
    throw new DatabaseOperationException("Error while reading from the
database", ex);
}

Rijk J.C. van Haaften
    /**
     * Determines whether the given dyna bean is stored in the database.
     * 
     * @param dynaBean   The bean
     * @param connection The connection
     * @return <code>true</code> if this dyna bean has a primary key
     */
    protected boolean exists(Connection connection, Database model, DynaBean 
dynaBean)
    {
        SqlDynaClass      dynaClass   = model.getDynaClassFor(dynaBean);
        SqlDynaProperty[] primaryKeys = dynaClass.getPrimaryKeyProperties();
        
        if (primaryKeys.length == 0)
        {
            return false;
        }
        
        String tableName = 
_builder.getDelimitedIdentifier(dynaClass.getTable().getName());
        StringBuilder sql = new StringBuilder("SELECT * FROM " + tableName + " 
WHERE ");
        
        for (int i = 0; i < primaryKeys.length; i++)
        {
            if (i > 0)
            {
                sql.append(" AND ");
            }
            String key = primaryKeys[i].getColumn().getName();
            sql.append(_builder.getDelimitedIdentifier(key));
            sql.append('=');
            sql.append('\'');
            sql.append(dynaBean.get(key));
            sql.append('\'');
        }
        
        try
        {
            return 
connection.createStatement().executeQuery(sql.toString()).next();
        }
        catch (SQLException ex)
        {
            throw new DatabaseOperationException("Error while reading from the 
database", ex);
        }
    }

    /**
     * [EMAIL PROTECTED]
     */
    public void store(Database model, DynaBean dynaBean) throws 
DatabaseOperationException
    {
        Connection connection = borrowConnection();
        
        try
        {
            if (exists(connection, model, dynaBean))
            {
                update(connection, model, dynaBean);
            }
            else
            {
                insert(connection, model, dynaBean);
            }
        }
        finally
        {
            returnConnection(connection);
        }
    }

Reply via email to