record.java

来自「Town是一个100% 纯Java API」· Java 代码 · 共 1,408 行 · 第 1/3 页

JAVA
1,408
字号
        {
            String attrib = parentDataSet.getKeyDef ().getAttrib(i);

            if (! isValueClean(attrib))
                throw new DataSetException (
                        "You cannot do a refresh from the database if the value " +
                        "for a KeyDef column has been changed with a Record.setValue().");

            if (! comma)
            {
                iss2.append (attrib);
                iss2.append (" = ?");
                comma = true;
            }
            else
            {
                iss2.append (" AND ");
                iss2.append (attrib);
                iss2.append (" = ?");
            }
        }
        return "SELECT " + iss1.toString() + " FROM " +
                parentDataSet.getTableName () + " WHERE " + iss2.toString();
    }
    /**
       Gets the appropriate SQL string for this record.

       @return SQL string
     */
    public String getSaveString() throws DataSetException,
    ConnectionException
    {
        if (toBeSavedWithInsert())
        {
            return getInsertSaveString();
        }
        else if (toBeSavedWithUpdate())
        {
            return getUpdateSaveString();
        }
        else if (toBeSavedWithDelete())
        {
            return getDeleteSaveString();
        }
        else
        {
            throw new DataSetException (
                    "Not able to return save string: " + this.saveType);
        }
    }
    /**
        Gets the schema for the parent DataSet

        @return the schema for the parent DataSet
      */
    public Schema getSchema() throws DataSetException
    {
        if (parentDataSet != null)
        {
            return parentDataSet.schema;
        }
        throw new DataSetException ("Internal Error: Record DataSet is null");
    }
    /**
        Builds the SQL UPDATE statement for this Record
        @return SQL UPDATE statement
      */
    private String getUpdateSaveString() throws DataSetException,
    ConnectionException
    {
        KeyDef kd = parentDataSet.getKeyDef ();
        if (kd == null || kd.size() == 0)
            throw new DataSetException ("You must specify KeyDef attributes for this TableDataSet in order to create a Record for update.");
        else if (isRecordClean())
            throw new DataSetException ("You must Record.setValue() on a column before doing an update.");

        StringBuffer iss1 = new StringBuffer (256);
        StringBuffer iss2 = new StringBuffer (256);
        boolean comma = false;

        for (int i = 1; i <= size(); i++)
        {
            Value val = getValue (i);
            if (! isValueClean(i) &&
                    ! schema.getColumn(i).readOnly())
            {
                if (! comma)
                {
                    iss1.append (schema.getColumn(i).name());
                    iss1.append (" = ?");
                    comma = true;
                }
                else
                {
                    iss1.append (", ");
                    iss1.append (schema.getColumn(i).name());
                    iss1.append (" = ?");
                }
            }
        }

        comma = false;

        for (int i = 1; i <= kd.size(); i++)
        {
            String attrib = kd.getAttrib(i);

            //if (! isValueClean (schema.index (attrib)))
            //    throw new DataSetException ("The value for column '" +
            //            attrib + "' is a key value and cannot be updated.");

            if (! comma)
            {
                iss2.append (attrib);
                iss2.append (" = ?");
                comma = true;
            }
            else
            {
                iss2.append (" AND ");
                iss2.append (attrib);
                iss2.append (" = ?");
            }
        }

        return "UPDATE " + parentDataSet.getTableName () + " SET " +
                iss1.toString() + " WHERE " + iss2.toString();
    }
    /**
        gets the value at index i
        @return the Value object at index i
      */
    public Value getValue (int i) throws DataSetException
    {
        if (i == 0)
            throw new DataSetException ("Values are 1 based!");
        else if (i > size())
            throw new DataSetException ("Only " + size() + " columns exist!");
        else if (values[i] == null)
            throw new DataSetException ("No values for the requested column!");

        return values[i];
    }
    /**
        gets the original keydef value at index i
        @return the original Value object at index i
      */
    public Value getOrigValue (int i) throws DataSetException
    {
		KeyDef kd = parentDataSet.getKeyDef ();
		if (i == 0)
            throw new DataSetException ("Values are 1 based!");
		else if (kd == null)
			throw new DataSetException ("Keydef not defined!");
        else if (i > kd.size())
            throw new DataSetException ("Only " + size() + " keydef columns exist!");
        else if (keydefValues[i] == null)
            throw new DataSetException ("No values for the requested column!");

        return keydefValues[i];
    }
    public Value getValue (String columnName) throws DataSetException
    {
        return getValue(schema.index (columnName));
    }
    public Value getOrigValue (String columnName) throws DataSetException
    {
		KeyDef kd = parentDataSet.getKeyDef ();
		if (kd == null)
			throw new DataSetException ("Keydef not defined!");
		for (int i = 1; i <= kd.size (); i++)
		{
			if (kd.getAttrib (i).equals (columnName))
				return getOrigValue (i);
		}
        throw new DataSetException ("Key Column name: " + columnName + " does not exist!");
    }
    /**
        Performs initialization for this Record.
      */
    private void initializeRecord() throws DataSetException
    {
        this.schema = getSchema ();
        this.numberOfColumns = schema.numberOfColumns();
        this.values = new Value[size() + 1];
        this.isClean = new boolean[size() + 1];
        setSaveType(Enums.UNKNOWN);
		
        for (int i = 1; i <= size(); i++)
        {
            markValueClean(i);
            this.values[i] = null;
        }
		
		if (parentDataSet instanceof TableDataSet)
		{
	        KeyDef kd = parentDataSet.getKeyDef();
			this.keydefValues = new Value[kd.size () + 1];
			for (int i = 1; i <= kd.size(); i++)
				keydefValues[i] = null;
		}
    }
    /**
        Determines if this record is a Zombie. A Zombie is a record that has been deleted from the
        database, but not yet removed from the DataSet.

        @return a boolean
      */
    public boolean isAZombie()
    {
        return (this.saveType == Enums.ZOMBIE) ? true : false;
    }
    /**
        If the record is not clean, needs to be saved with an Update, Delete or Insert, it returns true.

        @return boolean
      */
    public boolean isDirty ()
    {
        if (!isAZombie() || !isRecordClean() || toBeSavedWithUpdate() ||
                toBeSavedWithDelete() || toBeSavedWithInsert())
            return true;
        else
            return false;
    }
    /**
        Goes through all the values in the record to determine if it is clean or not.

        @return true if clean
      */
    public boolean isRecordClean()
    {
        for (int i = 1; i <= size(); i++)
        {
            if (isValueClean(i) == false)
                return false;
        }
        return true;
    }
    /**
        Determines whether or not a value stored in the record is clean.

        @return true if clean
      */
    public boolean isValueClean(int i)
    {
        return isClean[i];
    }
    /**
        Determines whether or not a value stored in the record is clean.

        @return true if clean
      */
    public boolean isValueClean(String column) throws DataSetException
    {
        return isClean[getValue (column).columnNumber()];
    }
    /**
        Marks this record to be inserted when a save is executed.
      */
    public void markForInsert() throws DataSetException
    {
        if (parentDataSet instanceof QueryDataSet)
            throw new DataSetException ("You cannot mark a record in a QueryDataSet for insert");

        setSaveType (Enums.INSERT);
    }
    /**
        Marks this record to be updated when a save is executed.
      */
    public void markForUpdate() throws DataSetException
    {
        if (parentDataSet instanceof QueryDataSet)
            throw new DataSetException ("You cannot mark a record in a QueryDataSet for update");

        setSaveType (Enums.UPDATE);
    }
    /**
       * Marks all the values in this record as clean.
       *
       */
    public void markRecordClean() throws DataSetException
    {
        for (int i = 1; i <= size(); i++)
        {
            markValueClean(i);
        }
    }
    /**
        Marks this record to be deleted when a save is executed.
      */
    public Record markToBeDeleted() throws DataSetException
    {
        if (parentDataSet instanceof QueryDataSet)
            throw new DataSetException ("You cannot mark a record in a QueryDataSet for deletion");

        setSaveType (Enums.DELETE);
        return this;
    }
    /**
        marks a value at a given position as clean.
      */
    public void markValueClean (int pos) throws DataSetException
    {
        if (pos == 0)
            throw new DataSetException ("Value position must be greater than 0.");
        else if (pos > size())
            throw new DataSetException ("Value position is greater than number of values.");

        this.isClean[pos] = true;
    }
    /**
        marks a value with a given column name as clean.
      */
    public void markValueClean (String columnName) throws DataSetException
    {
        markValueClean (schema.index(columnName));
    }
    /**
        marks a value at a given position as dirty.
      */
    public void markValueDirty (int pos) throws DataSetException
    {
        if (pos == 0)
            throw new DataSetException ("Value position must be greater than 0.");
        else if (pos > size())
            throw new DataSetException ("Value position is greater than number of values.");

        this.isClean[pos] = false;
    }
    /**
        marks a value with a given column name as dirty.
      */
    public void markValueDirty (String columnName) throws DataSetException
    {
        markValueDirty (schema.index(columnName));
    }
    /**
       * This method refreshes this Record's Value's. It can only be performed on
       * a Record that has not been modified and has been created with a TableDataSet
       * and corresponding KeyDef.
       *
       * @param   connection
       * @exception   DataSetException
       * @exception   ConnectionException
       */
    public void refresh (Connection connection)
            throws DataSetException, ConnectionException
    {
        if (toBeSavedWithDelete())
            return;
        else if (toBeSavedWithInsert())
            throw new DataSetException ("There is no way to refresh a record which has been created with addRecord().");
        else if (parentDataSet instanceof QueryDataSet)
            throw new DataSetException ("You can only perform a refresh on Records created with a TableDataSet.");

        PreparedStatement stmt = null;
        try
        {
            stmt = connection.prepareStatement (getRefreshQueryString());
            int ps = 1;
            for (int i = 1; i <= parentDataSet.getKeyDef ().size(); i++)
            {
                Value val = getValue (
                        parentDataSet.getKeyDef ().getAttrib(i));

                val.setPreparedStatementValue (stmt, ps++);
            }

            ResultSet rs = stmt.executeQuery();
            rs.next();

            initializeRecord();

            createValues(rs);
        }
        catch (SQLException e1)
        {
            throw new ConnectionException (e1);
        }
        finally { try
            {
                if (stmt != null)
                    stmt.close();
            }
            catch (SQLException e2)
            {
                throw new ConnectionException (e2);
            }
        } }
    /**
        Saves the data in this Record to the database. Uses the parent dataset's connection.
        @return 1 if the save completed. 0 otherwise.
      */
    public int save() throws DataSetException, ConnectionException
    {
        return save (parentDataSet.connection());
    }
    /**
        Saves the data in this Record to the database. Uses the connection passed into it.
        @return 1 if the save completed. 0 otherwise.
      */
    public int save (Connection connection) throws DataSetException,
    ConnectionException
    {
        int returnValue = 0;

        if (parentDataSet instanceof QueryDataSet)
            throw new DataSetException ("You cannot save a QueryDataSet. Please use a TableDataSet instead.");

        if (! isDirty ())
            return returnValue;

        if (toBeSavedWithInsert())
            returnValue = saveWithInsert (connection);
        else if (toBeSavedWithUpdate())
            returnValue = saveWithUpdate (connection);
        else if (toBeSavedWithDelete())
            returnValue = saveWithDelete (connection);

        return returnValue;
    }
    /**
        Saves the data in this Record to the database with an DELETE statement
        @return SQL DELETE statement
      */
    private int saveWithDelete (Connection connection)
            throws DataSetException, ConnectionException
    {
        PreparedStatement stmt = null;
        try
        {
            stmt = connection.prepareStatement (getSaveString());
            int ps = 1;
            for (int i = 1; i <= parentDataSet.getKeyDef ().size(); i++)
            {
                //Value val = getValue (parentDataSet.getKeyDef ().getAttrib(i));
				Value val = getOrigValue (parentDataSet.getKeyDef ().getAttrib(i));
				
                val.setPreparedStatementValue (stmt, ps++);
            }

            int ret = stmt.executeUpdate();

            setSaveType (Enums.ZOMBIE);

            ((TableDataSet) parentDataSet).removeDeletedRecords();

            if (ret > 1)
           		throw new ConnectionException ("There were " + ret + " rows deleted with this records key value.");

            return ret;
        }
        catch (SQLException e1)
        {
            throw new ConnectionException (e1);
        }
        finally { try
            {
                if (stmt != null)
                    stmt.close();
            }
            catch (SQLException e2)
            {
                throw new ConnectionException (e2);
            }
        } }
    /**
        Saves the data in this Record to the database with an INSERT statement
        @return SQL INSERT statement

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?