|
Spec-Zone .ru
спецификации, руководства, описания, API
|
public interface SyncResolver extends RowSet
Отметьте, что конфликт является ситуацией где RowSet исходные значения объекта для строки не соответствуют значения в источнике данных, который указывает, что строка источника данных была изменена начиная с последней синхронизации. Отметьте также это a RowSet исходные значения объекта являются значениями, которые это имело только до последняя синхронизация, которые являются не обязательно ее начальными значениями.
SyncResolver ОбъектSyncResolver объект является специализированным RowSet возразите что реализации SyncResolver интерфейс. Это может работать как любой соединенный RowSet объект (реализация JdbcRowSet интерфейс) или соединенный RowSet объект (реализация CachedRowSet взаимодействуйте через интерфейс или один из его подынтерфейсов). Для получения информации о подынтерфейсах см. javax.sql.rowset описание пакета. Ссылочная реализация для SyncResolver реализации CachedRowSet интерфейс, но другие реализации может хотеть реализовывать JdbcRowSet интерфейс, чтобы удовлетворить определенные потребности. После того, как приложение попыталось синхронизировать a RowSet объект с источником данных (вызывая CachedRowSet метод acceptChanges), и один или более конфликтов были найдены, набор строк SyncProvider объект создает экземпляр SyncResolver. Это новое SyncResolver у объекта есть то же самое число строк и столбцов как RowSet объект, который делал попытку синхронизации. SyncResolver объект содержит значения от источника данных, который вызвал конфликт (ы) и null для всех других значений. Кроме того, это содержит информацию о каждом конфликте.
SyncResolver ОбъектacceptChanges встречается с конфликтами, SyncProvider объект создает a SyncProviderException объект и наборы это с новым SyncResolver объект. Метод acceptChanges выдаст это исключение, которое приложение может тогда поймать и использовать, чтобы получить SyncResolver объект это содержит. Следующий фрагмент кода использует SyncProviderException метод getSyncResolver добраться SyncResolver объектный преобразователь.
} catch (SyncProviderException spe) {
SyncResolver resolver = spe.getSyncResolver();
...
}
С преобразователем в руке приложение может использовать это, чтобы получить информацию, которую это содержит о конфликте или конфликтах. A SyncResolver объект, такой как преобразователь, отслеживает конфликты для каждой строки, в которой есть конфликт. Это также помещает блокировку в таблицу или таблицы, на которые влияет команда набора строк так, чтобы больше конфликтов не могло произойти, в то время как текущие конфликты разрешаются.
Следующие виды информации могут быть получены из a SyncResolver объект:
SyncProvider интерфейс определяет четыре константы, описывающие состояния, которые могут произойти. Три константы описывают тип работы (обновление, удалите, или вставьте), это a RowSet объект пытался выполнить, когда конфликт был обнаружен, и четвертое указывает, что нет никакого конфликта. Эти константы являются возможными возвращаемыми значениями когда a SyncResolver возразите вызывает метод getStatus.
int operation = resolver.getStatus();
RowSet объект изменился и пытается записать в источник данных, был также изменен в источнике данных начиная с последней синхронизации. Приложение может вызвать SyncResolver метод getConflictValue получать значение в источнике данных, который является причиной конфликта потому что значения в a SyncResolver объект является значениями конфликта от источника данных.
java.lang.Object conflictValue = resolver.getConflictValue(2);
Отметьте, что столбец в преобразователе может определяться номером столбца, как делается в предыдущей строке кода, или именем столбца.
С информацией, полученной от методов getStatus и getConflictValue, приложение может сделать определение, относительно которого значение должно быть сохранено в источнике данных. Приложение тогда вызывает SyncResolver метод setResolvedValue, который устанавливает значение, которое будет сохранено в RowSet возразите и также в источнике данных.
resolver.setResolvedValue("DEPT", 8390426);
В предыдущей строке кода имя столбца определяет столбец в RowSet объект, который должен быть установлен с данным значением. Номер столбца может также использоваться, чтобы определять столбец. Приложение вызывает метод setResolvedValue после того, как это разрешило все конфликты в текущей строке конфликта и повторяет этот процесс для каждой строки конфликта в SyncResolver объект.
SyncResolver ОбъектSyncResolver объект является a RowSet объект, приложение может использовать весь из RowSet методы для того, чтобы переместить курсор, чтобы переместиться по a SyncResolver объект. Например, приложение может использовать RowSet метод next добраться до каждой строки и затем вызвать SyncResolver метод getStatus видеть, содержит ли строка конфликт. Подряд с одним или более конфликтами, приложение может выполнить итерации через столбцы, чтобы найти любые ненулевые значения, которые будут значениями от источника данных, которые находятся в конфликте. Облегчить перемещаться по a SyncResolver объект, особенно когда есть большие количества строк без конфликтов, SyncResolver интерфейс определяет методы nextConflict и previousConflict, которые перемещаются только в строки, которые содержат по крайней мере одно значение конфликта. Затем приложение может вызвать SyncResolver метод getConflictValue, предоставление этого с номером столбца, чтобы получить конфликт ценят себя. Фрагмент кода в следующем разделе дает пример.
RowSet объект crs мог бы попытаться синхронизировать себя с базовым источником данных и затем разрешить конфликты. В try блок, crs вызывает метод acceptChanges, передача этого Connection объектный довод "против". Если нет никаких конфликтов, изменения в crs просто пишутся источнику данных. Однако, если есть конфликт, метод acceptChanges броски a SyncProviderException объект, и catch блок вступает в силу. В этом примере, который иллюстрирует один из многих путей a SyncResolver объект может использоваться, SyncResolver метод nextConflict используется в a while цикл. Цикл закончится когда nextConflict возвраты false, который произойдет, когда не будет больше строк конфликта в SyncResolver объектный преобразователь. В Этом определенном фрагменте кода преобразователь ищет строки, у которых есть конфликты обновления (строки с состоянием SyncResolver.UPDATE_ROW_CONFLICT), и остальная часть этого фрагмента кода выполняется только для строк, где конфликты произошли, потому что crs делал попытку обновления. После того, как курсор для преобразователя переместился в следующую строку конфликта, у которой есть конфликт обновления, метод getRow указывает на число текущей строки, и курсор для CachedRowSet объект crs перемещается в сопоставимую строку в crs. Выполняя итерации через столбцы той строки и в преобразователе и в crs, конфликтные значения могут быть получены и сравнены, чтобы решить, какой должен быть сохранен. В этом фрагменте кода значение в crs является набором того как разрешенным значением, что означает, что это будет использоваться, чтобы перезаписать значение конфликта в источнике данных.
try {
crs.acceptChanges(con);
} catch (SyncProviderException spe) {
SyncResolver resolver = spe.getSyncResolver();
Object crsValue; // value in the RowSet object
Object resolverValue: // value in the SyncResolver object
Object resolvedValue: // value to be persisted
while(resolver.nextConflict()) {
if(resolver.getStatus() == SyncResolver.UPDATE_ROW_CONFLICT) {
int row = resolver.getRow();
crs.absolute(row);
int colCount = crs.getMetaData().getColumnCount();
for(int j = 1; j <= colCount; j++) {
if (resolver.getConflictValue(j) != null) {
crsValue = crs.getObject(j);
resolverValue = resolver.getConflictValue(j);
. . .
// compare crsValue and resolverValue to determine
// which should be the resolved value (the value to persist)
resolvedValue = crsValue;
resolver.setResolvedValue(j, resolvedValue);
}
}
}
}
}
| Modifier and Type | Field and Description |
|---|---|
static int |
DELETE_ROW_CONFLICT
Indicates that a conflict occurred while the
RowSet object was
attempting to delete a row in the data source. |
static int |
INSERT_ROW_CONFLICT
Indicates that a conflict occurred while the
RowSet object was
attempting to insert a row into the data source. |
static int |
NO_ROW_CONFLICT
Indicates that no conflict occured while the
RowSet object
was attempting to update, delete or insert a row in the data source. |
static int |
UPDATE_ROW_CONFLICT
Indicates that a conflict occurred while the
RowSet object was
attempting to update a row in the data source. |
CLOSE_CURSORS_AT_COMMIT, CONCUR_READ_ONLY, CONCUR_UPDATABLE, FETCH_FORWARD, FETCH_REVERSE, FETCH_UNKNOWN, HOLD_CURSORS_OVER_COMMIT, TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, TYPE_SCROLL_SENSITIVE| Modifier and Type | Method and Description |
|---|---|
Объект |
getConflictValue(int index)
Retrieves the value in the designated column in the current row of this
SyncResolver object, which is the value in the data source
that caused a conflict. |
Объект |
getConflictValue(String columnName)
Retrieves the value in the designated column in the current row of this
SyncResolver object, which is the value in the data source
that caused a conflict. |
int |
getStatus()
Retrieves the conflict status of the current row of this
SyncResolver,
which indicates the operation
the RowSet object was attempting when the conflict occurred. |
boolean |
nextConflict()
Moves the cursor down from its current position to the next row that contains
a conflict value.
|
boolean |
previousConflict()
Moves the cursor up from its current position to the previous conflict
row in this
SyncResolver object. |
void |
setResolvedValue(int index,
Object obj)
Sets obj as the value in column index in the current row of the
RowSet object that is being synchronized. |
void |
setResolvedValue(String columnName,
Object obj)
Sets obj as the value in column columnName in the current row of the
RowSet object that is being synchronized. |
addRowSetListener, clearParameters, execute, getCommand, getDataSourceName, getEscapeProcessing, getMaxFieldSize, getMaxRows, getPassword, getQueryTimeout, getTransactionIsolation, getTypeMap, getUrl, getUsername, isReadOnly, removeRowSetListener, setArray, setAsciiStream, setAsciiStream, setAsciiStream, setAsciiStream, setBigDecimal, setBigDecimal, setBinaryStream, setBinaryStream, setBinaryStream, setBinaryStream, setBlob, setBlob, setBlob, setBlob, setBlob, setBlob, setBoolean, setBoolean, setByte, setByte, setBytes, setBytes, setCharacterStream, setCharacterStream, setCharacterStream, setCharacterStream, setClob, setClob, setClob, setClob, setClob, setClob, setCommand, setConcurrency, setDataSourceName, setDate, setDate, setDate, setDate, setDouble, setDouble, setEscapeProcessing, setFloat, setFloat, setInt, setInt, setLong, setLong, setMaxFieldSize, setMaxRows, setNCharacterStream, setNCharacterStream, setNCharacterStream, setNCharacterStream, setNClob, setNClob, setNClob, setNClob, setNClob, setNClob, setNString, setNString, setNull, setNull, setNull, setNull, setObject, setObject, setObject, setObject, setObject, setObject, setPassword, setQueryTimeout, setReadOnly, setRef, setRowId, setRowId, setShort, setShort, setSQLXML, setSQLXML, setString, setString, setTime, setTime, setTime, setTime, setTimestamp, setTimestamp, setTimestamp, setTimestamp, setTransactionIsolation, setType, setTypeMap, setURL, setUrl, setUsernameabsolute, afterLast, beforeFirst, cancelRowUpdates, clearWarnings, close, deleteRow, findColumn, first, getArray, getArray, getAsciiStream, getAsciiStream, getBigDecimal, getBigDecimal, getBigDecimal, getBigDecimal, getBinaryStream, getBinaryStream, getBlob, getBlob, getBoolean, getBoolean, getByte, getByte, getBytes, getBytes, getCharacterStream, getCharacterStream, getClob, getClob, getConcurrency, getCursorName, getDate, getDate, getDate, getDate, getDouble, getDouble, getFetchDirection, getFetchSize, getFloat, getFloat, getHoldability, getInt, getInt, getLong, getLong, getMetaData, getNCharacterStream, getNCharacterStream, getNClob, getNClob, getNString, getNString, getObject, getObject, getObject, getObject, getObject, getObject, getRef, getRef, getRow, getRowId, getRowId, getShort, getShort, getSQLXML, getSQLXML, getStatement, getString, getString, getTime, getTime, getTime, getTime, getTimestamp, getTimestamp, getTimestamp, getTimestamp, getType, getUnicodeStream, getUnicodeStream, getURL, getURL, getWarnings, insertRow, isAfterLast, isBeforeFirst, isClosed, isFirst, isLast, last, moveToCurrentRow, moveToInsertRow, next, previous, refreshRow, relative, rowDeleted, rowInserted, rowUpdated, setFetchDirection, setFetchSize, updateArray, updateArray, updateAsciiStream, updateAsciiStream, updateAsciiStream, updateAsciiStream, updateAsciiStream, updateAsciiStream, updateBigDecimal, updateBigDecimal, updateBinaryStream, updateBinaryStream, updateBinaryStream, updateBinaryStream, updateBinaryStream, updateBinaryStream, updateBlob, updateBlob, updateBlob, updateBlob, updateBlob, updateBlob, updateBoolean, updateBoolean, updateByte, updateByte, updateBytes, updateBytes, updateCharacterStream, updateCharacterStream, updateCharacterStream, updateCharacterStream, updateCharacterStream, updateCharacterStream, updateClob, updateClob, updateClob, updateClob, updateClob, updateClob, updateDate, updateDate, updateDouble, updateDouble, updateFloat, updateFloat, updateInt, updateInt, updateLong, updateLong, updateNCharacterStream, updateNCharacterStream, updateNCharacterStream, updateNCharacterStream, updateNClob, updateNClob, updateNClob, updateNClob, updateNClob, updateNClob, updateNString, updateNString, updateNull, updateNull, updateObject, updateObject, updateObject, updateObject, updateObject, updateObject, updateObject, updateObject, updateRef, updateRef, updateRow, updateRowId, updateRowId, updateShort, updateShort, updateSQLXML, updateSQLXML, updateString, updateString, updateTime, updateTime, updateTimestamp, updateTimestamp, wasNullisWrapperFor, unwrapstatic final int UPDATE_ROW_CONFLICT
RowSet object was
attempting to update a row in the data source.
The values in the data source row to be updated differ from the
RowSet object's original values for that row, which means that
the row in the data source has been updated or deleted since the last
synchronization.static final int DELETE_ROW_CONFLICT
RowSet object was
attempting to delete a row in the data source.
The values in the data source row to be updated differ from the
RowSet object's original values for that row, which means that
the row in the data source has been updated or deleted since the last
synchronization.static final int INSERT_ROW_CONFLICT
RowSet object was
attempting to insert a row into the data source. This means that a
row with the same primary key as the row to be inserted has been inserted
into the data source since the last synchronization.static final int NO_ROW_CONFLICT
RowSet object
was attempting to update, delete or insert a row in the data source. The values in
the SyncResolver will contain null values only as an indication
that no information in pertitent to the conflict resolution in this row.int getStatus()
SyncResolver,
which indicates the operation
the RowSet object was attempting when the conflict occurred.SyncResolver.UPDATE_ROW_CONFLICT,
SyncResolver.DELETE_ROW_CONFLICT,
SyncResolver.INSERT_ROW_CONFLICT, or
SyncResolver.NO_ROW_CONFLICTObject getConflictValue(int index) throws SQLException
SyncResolver object, which is the value in the data source
that caused a conflict.index - an int designating the column in this row of this
SyncResolver object from which to retrieve the value
causing a conflictSyncResolver objectSQLException - if a database access error occursObject getConflictValue(String columnName) throws SQLException
SyncResolver object, which is the value in the data source
that caused a conflict.columnName - a String object designating the column in this row of this
SyncResolver object from which to retrieve the value
causing a conflictSyncResolver objectSQLException - if a database access error occursvoid setResolvedValue(int index,
Object obj)
throws SQLException
RowSet object that is being synchronized. obj
is set as the value in the data source internally.index - an int giving the number of the column into which to
set the value to be persistedobj - an Object that is the value to be set in the
RowSet object and persisted in the data sourceSQLException - if a database access error occursvoid setResolvedValue(String columnName, Object obj) throws SQLException
RowSet object that is being synchronized. obj
is set as the value in the data source internally.columnName - a String object giving the name of the column
into which to set the value to be persistedobj - an Object that is the value to be set in the
RowSet object and persisted in the data sourceSQLException - if a database access error occursboolean nextConflict()
throws SQLException
SyncResolver object's
cursor is initially positioned before the first conflict row; the first call to the
method nextConflict makes the first conflict row the current row;
the second call makes the second conflict row the current row, and so on.
A call to the method nextConflict will implicitly close
an input stream if one is open and will clear the SyncResolver
object's warning chain.
true if the new current row is valid; false
if there are no more rowsSQLException - if a database access error occurs or the result set type
is TYPE_FORWARD_ONLYboolean previousConflict()
throws SQLException
SyncResolver object.
A call to the method previousConflict will implicitly close
an input stream if one is open and will clear the SyncResolver
object's warning chain.
true if the cursor is on a valid row; false
if it is off the result setSQLException - if a database access error occurs or the result set type
is TYPE_FORWARD_ONLY
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2013, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b92