-
- All Superinterfaces:
AutoCloseable,Joinable,ResultSet,RowSet,Wrapper
- All Known Subinterfaces:
FilteredRowSet,JoinRowSet,WebRowSet
public interface CachedRowSet extends RowSet, Joinable
The interface that all standard implementations ofCachedRowSetmust implement.The reference implementation of the
CachedRowSetinterface provided by Oracle Corporation is a standard implementation. Developers may use this implementation just as it is, they may extend it, or they may choose to write their own implementations of this interface.A
CachedRowSetobject is a container for rows of data that caches its rows in memory, which makes it possible to operate without always being connected to its data source. Further, it is a JavaBeans™ component and is scrollable, updatable, and serializable. ACachedRowSetobject typically contains rows from a result set, but it can also contain rows from any file with a tabular format, such as a spread sheet. The reference implementation supports getting data only from aResultSetobject, but developers can extend theSyncProviderimplementations to provide access to other tabular data sources.An application can modify the data in a
CachedRowSetobject, and those modifications can then be propagated back to the source of the data.A
CachedRowSetobject is a disconnected rowset, which means that it makes use of a connection to its data source only briefly. It connects to its data source while it is reading data to populate itself with rows and again while it is propagating changes back to its underlying data source. The rest of the time, aCachedRowSetobject is disconnected, including while its data is being modified. Being disconnected makes aRowSetobject much leaner and therefore much easier to pass to another component. For example, a disconnectedRowSetobject can be serialized and passed over the wire to a thin client such as a personal digital assistant (PDA).1.0 Creating a
The following line of code uses the default constructor forCachedRowSetObjectCachedRowSetsupplied in the reference implementation (RI) to create a defaultCachedRowSetobject.CachedRowSetImpl crs = new CachedRowSetImpl();This newCachedRowSetobject will have its properties set to the default properties of aBaseRowSetobject, and, in addition, it will have anRIOptimisticProviderobject as its synchronization provider.RIOptimisticProvider, one of twoSyncProviderimplementations included in the RI, is the default provider that theSyncFactorysingleton will supply when no synchronization provider is specified.A
SyncProviderobject provides aCachedRowSetobject with a reader (aRowSetReaderobject) for reading data from a data source to populate itself with data. A reader can be implemented to read data from aResultSetobject or from a file with a tabular format. ASyncProviderobject also provides a writer (aRowSetWriterobject) for synchronizing any modifications to theCachedRowSetobject's data made while it was disconnected with the data in the underlying data source.A writer can be implemented to exercise various degrees of care in checking for conflicts and in avoiding them. (A conflict occurs when a value in the data source has been changed after the rowset populated itself with that value.) The
RIOptimisticProviderimplementation assumes there will be few or no conflicts and therefore sets no locks. It updates the data source with values from theCachedRowSetobject only if there are no conflicts. Other writers can be implemented so that they always write modified data to the data source, which can be accomplished either by not checking for conflicts or, on the other end of the spectrum, by setting locks sufficient to prevent data in the data source from being changed. Still other writer implementations can be somewhere in between.A
CachedRowSetobject may use anySyncProviderimplementation that has been registered with theSyncFactorysingleton. An application can find out whichSyncProviderimplementations have been registered by calling the following line of code.java.util.Enumeration providers = SyncFactory.getRegisteredProviders();There are two ways for a
CachedRowSetobject to specify whichSyncProviderobject it will use.- Supplying the name of the implementation to the constructor
The following line of code creates theCachedRowSetobject crs2 that is initialized with default values except that itsSyncProviderobject is the one specified.CachedRowSetImpl crs2 = new CachedRowSetImpl( "com.fred.providers.HighAvailabilityProvider"); - Setting the
SyncProviderusing theCachedRowSetmethodsetSyncProvider
The following line of code resets theSyncProviderobject for crs, theCachedRowSetobject created with the default constructor.crs.setSyncProvider("com.fred.providers.HighAvailabilityProvider");
SyncFactoryandSyncProviderfor more details.2.0 Retrieving Data from a
Data is retrieved from aCachedRowSetObjectCachedRowSetobject by using the getter methods inherited from theResultSetinterface. The following examples, in whichcrsis aCachedRowSetobject, demonstrate how to iterate through the rows, retrieving the column values in each row. The first example uses the version of the getter methods that take a column number; the second example uses the version that takes a column name. Column numbers are generally used when theRowSetobject's command is of the formSELECT * FROM TABLENAME; column names are most commonly used when the command specifies columns by name.while (crs.next()) { String name = crs.getString(1); int id = crs.getInt(2); Clob comment = crs.getClob(3); short dept = crs.getShort(4); System.out.println(name + " " + id + " " + comment + " " + dept); }while (crs.next()) { String name = crs.getString("NAME"); int id = crs.getInt("ID"); Clob comment = crs.getClob("COM"); short dept = crs.getShort("DEPT"); System.out.println(name + " " + id + " " + comment + " " + dept); }2.1 Retrieving
An application can get information about the columns in aRowSetMetaDataCachedRowSetobject by callingResultSetMetaDataandRowSetMetaDatamethods on aRowSetMetaDataobject. The following code fragment, in which crs is aCachedRowSetobject, illustrates the process. The first line creates aRowSetMetaDataobject with information about the columns in crs. The methodgetMetaData, inherited from theResultSetinterface, returns aResultSetMetaDataobject, which is cast to aRowSetMetaDataobject before being assigned to the variable rsmd. The second line finds out how many columns jrs has, and the third line gets the JDBC type of values stored in the second column ofjrs.RowSetMetaData rsmd = (RowSetMetaData)crs.getMetaData(); int count = rsmd.getColumnCount(); int type = rsmd.getColumnType(2);TheRowSetMetaDatainterface differs from theResultSetMetaDatainterface in two ways.- It includes
settermethods: ARowSetobject uses these methods internally when it is populated with data from a differentResultSetobject. - It contains fewer
gettermethods: SomeResultSetMetaDatamethods to not apply to aRowSetobject. For example, methods retrieving whether a column value is writable or read only do not apply because all of aRowSetobject's columns will be writable or read only, depending on whether the rowset is updatable or not.
RowSetMetaDataobject, implementations must override thegetMetaData()method defined injava.sql.ResultSetand return aRowSetMetaDataobject.3.0 Updating a
Updating aCachedRowSetObjectCachedRowSetobject is similar to updating aResultSetobject, but because the rowset is not connected to its data source while it is being updated, it must take an additional step to effect changes in its underlying data source. After calling the methodupdateRoworinsertRow, aCachedRowSetobject must also call the methodacceptChangesto have updates written to the data source. The following example, in which the cursor is on a row in theCachedRowSetobject crs, shows the code required to update two column values in the current row and also update theRowSetobject's underlying data source.crs.updateShort(3, 58); crs.updateInt(4, 150000); crs.updateRow(); crs.acceptChanges();The next example demonstrates moving to the insert row, building a new row on the insert row, inserting it into the rowset, and then calling the method
acceptChangesto add the new row to the underlying data source. Note that as with the getter methods, the updater methods may take either a column index or a column name to designate the column being acted upon.crs.moveToInsertRow(); crs.updateString("Name", "Shakespeare"); crs.updateInt("ID", 10098347); crs.updateShort("Age", 58); crs.updateInt("Sal", 150000); crs.insertRow(); crs.moveToCurrentRow(); crs.acceptChanges();NOTE: Where the
insertRow()method inserts the contents of aCachedRowSetobject's insert row is implementation-defined. The reference implementation for theCachedRowSetinterface inserts a new row immediately following the current row, but it could be implemented to insert new rows in any number of other places.Another thing to note about these examples is how they use the method
acceptChanges. It is this method that propagates changes in aCachedRowSetobject back to the underlying data source, calling on theRowSetobject's writer internally to write changes to the data source. To do this, the writer has to incur the expense of establishing a connection with that data source. The preceding two code fragments call the methodacceptChangesimmediately after callingupdateRoworinsertRow. However, when there are multiple rows being changed, it is more efficient to callacceptChangesafter all calls toupdateRowandinsertRowhave been made. IfacceptChangesis called only once, only one connection needs to be established.4.0 Updating the Underlying Data Source
When the methodacceptChangesis executed, theCachedRowSetobject's writer, aRowSetWriterImplobject, is called behind the scenes to write the changes made to the rowset to the underlying data source. The writer is implemented to make a connection to the data source and write updates to it.A writer is made available through an implementation of the
SyncProviderinterface, as discussed in section 1, "Creating aCachedRowSetObject." The default reference implementation provider,RIOptimisticProvider, has its writer implemented to use an optimistic concurrency control mechanism. That is, it maintains no locks in the underlying database while the rowset is disconnected from the database and simply checks to see if there are any conflicts before writing data to the data source. If there are any conflicts, it does not write anything to the data source.The reader/writer facility provided by the
SyncProviderclass is pluggable, allowing for the customization of data retrieval and updating. If a different concurrency control mechanism is desired, a different implementation ofSyncProvidercan be plugged in using the methodsetSyncProvider.In order to use the optimistic concurrency control routine, the
RIOptimisticProvidermaintains both its current value and its original value (the value it had immediately preceding the current value). Note that if no changes have been made to the data in aRowSetobject, its current values and its original values are the same, both being the values with which theRowSetobject was initially populated. However, once any values in theRowSetobject have been changed, the current values and the original values will be different, though at this stage, the original values are still the initial values. With any subsequent changes to data in aRowSetobject, its original values and current values will still differ, but its original values will be the values that were previously the current values.Keeping track of original values allows the writer to compare the
RowSetobject's original value with the value in the database. If the values in the database differ from theRowSetobject's original values, which means that the values in the database have been changed, there is a conflict. Whether a writer checks for conflicts, what degree of checking it does, and how it handles conflicts all depend on how it is implemented.5.0 Registering and Notifying Listeners
Being JavaBeans components, all rowsets participate in the JavaBeans event model, inheriting methods for registering listeners and notifying them of changes from theBaseRowSetclass. A listener for aCachedRowSetobject is a component that wants to be notified whenever there is a change in the rowset. For example, if aCachedRowSetobject contains the results of a query and those results are being displayed in, say, a table and a bar graph, the table and bar graph could be registered as listeners with the rowset so that they can update themselves to reflect changes. To become listeners, the table and bar graph classes must implement theRowSetListenerinterface. Then they can be added to theCachedRowSetobject's list of listeners, as is illustrated in the following lines of code.crs.addRowSetListener(table); crs.addRowSetListener(barGraph);EachCachedRowSetmethod that moves the cursor or changes data also notifies registered listeners of the changes, sotableandbarGraphwill be notified when there is a change incrs.6.0 Passing Data to Thin Clients
One of the main reasons to use aCachedRowSetobject is to pass data between different components of an application. Because it is serializable, aCachedRowSetobject can be used, for example, to send the result of a query executed by an enterprise JavaBeans component running in a server environment over a network to a client running in a web browser.While a
CachedRowSetobject is disconnected, it can be much leaner than aResultSetobject with the same data. As a result, it can be especially suitable for sending data to a thin client such as a PDA, where it would be inappropriate to use a JDBC driver due to resource limitations or security considerations. Thus, aCachedRowSetobject provides a means to "get rows in" without the need to implement the full JDBC API.7.0 Scrolling and Updating
A second major use forCachedRowSetobjects is to provide scrolling and updating forResultSetobjects that do not provide these capabilities themselves. In other words, aCachedRowSetobject can be used to augment the capabilities of a JDBC technology-enabled driver (hereafter called a "JDBC driver") when the DBMS does not provide full support for scrolling and updating. To achieve the effect of making a non-scrollable and read-onlyResultSetobject scrollable and updatable, a programmer simply needs to create aCachedRowSetobject populated with thatResultSetobject's data. This is demonstrated in the following code fragment, wherestmtis aStatementobject.ResultSet rs = stmt.executeQuery("SELECT * FROM EMPLOYEES"); CachedRowSetImpl crs = new CachedRowSetImpl(); crs.populate(rs);The object
crsnow contains the data from the tableEMPLOYEES, just as the objectrsdoes. The difference is that the cursor forcrscan be moved forward, backward, or to a particular row even if the cursor forrscan move only forward. In addition,crsis updatable even ifrsis not because by default, aCachedRowSetobject is both scrollable and updatable.In summary, a
CachedRowSetobject can be thought of as simply a disconnected set of rows that are being cached outside of a data source. Being thin and serializable, it can easily be sent across a wire, and it is well suited to sending data to a thin client. However, aCachedRowSetobject does have a limitation: It is limited in size by the amount of data it can store in memory at one time.8.0 Getting Universal Data Access
Another advantage of theCachedRowSetclass is that it makes it possible to retrieve and store data from sources other than a relational database. The reader for a rowset can be implemented to read and populate its rowset with data from any tabular data source, including a spreadsheet or flat file. Because both aCachedRowSetobject and its metadata can be created from scratch, a component that acts as a factory for rowsets can use this capability to create a rowset containing data from non-SQL data sources. Nevertheless, it is expected that most of the time,CachedRowSetobjects will contain data that was fetched from an SQL database using the JDBC API.9.0 Setting Properties
All rowsets maintain a set of properties, which will usually be set using a tool. The number and kinds of properties a rowset has will vary, depending on what the rowset does and how it gets its data. For example, rowsets that get their data from aResultSetobject need to set the properties that are required for making a database connection. If a rowset uses theDriverManagerfacility to make a connection, it needs to set a property for the JDBC URL that identifies the appropriate driver, and it needs to set the properties that give the user name and password. If, on the other hand, the rowset uses aDataSourceobject to make the connection, which is the preferred method, it does not need to set the property for the JDBC URL. Instead, it needs to set properties for the logical name of the data source, for the user name, and for the password.NOTE: In order to use a
DataSourceobject for making a connection, theDataSourceobject must have been registered with a naming service that uses the Java Naming and Directory Interface™ (JNDI) API. This registration is usually done by a person acting in the capacity of a system administrator.In order to be able to populate itself with data from a database, a rowset needs to set a command property. This property is a query that is a
PreparedStatementobject, which allows the query to have parameter placeholders that are set at run time, as opposed to design time. To set these placeholder parameters with values, a rowset provides setter methods for setting values of each data type, similar to the setter methods provided by thePreparedStatementinterface.The following code fragment illustrates how the
CachedRowSetobjectcrsmight have its command property set. Note that if a tool is used to set properties, this is the code that the tool would use.crs.setCommand("SELECT FIRST_NAME, LAST_NAME, ADDRESS FROM CUSTOMERS " + "WHERE CREDIT_LIMIT > ? AND REGION = ?");The values that will be used to set the command's placeholder parameters are contained in the
RowSetobject'sparamsfield, which is aVectorobject. TheCachedRowSetclass provides a set of setter methods for setting the elements in itsparamsfield. The following code fragment demonstrates setting the two parameters in the query from the previous example.crs.setInt(1, 5000); crs.setString(2, "West");The
paramsfield now contains two elements, each of which is an array two elements long. The first element is the parameter number; the second is the value to be set. In this case, the first element ofparamsis1,5000, and the second element is2,"West". When an application calls the methodexecute, it will in turn call on thisRowSetobject's reader, which will in turn invoke itsreadDatamethod. As part of its implementation,readDatawill get the values inparamsand use them to set the command's placeholder parameters. The following code fragment gives an idea of how the reader does this, after obtaining theConnectionobjectcon.PreparedStatement pstmt = con.prepareStatement(crs.getCommand()); reader.decodeParams(); // decodeParams figures out which setter methods to use and does something // like the following: // for (i = 0; i < params.length; i++) { // pstmt.setObject(i + 1, params[i]); // }At this point, the command for
crsis the query"SELECT FIRST_NAME, LAST_NAME, ADDRESS FROM CUSTOMERS WHERE CREDIT_LIMIT > 5000 AND REGION = "West". After thereadDatamethod executes this command with the following line of code, it will have the data fromrswith which to populatecrs.ResultSet rs = pstmt.executeQuery();The preceding code fragments give an idea of what goes on behind the scenes; they would not appear in an application, which would not invoke methods like
readDataanddecodeParams. In contrast, the following code fragment shows what an application might do. It sets the rowset's command, sets the command's parameters, and executes the command. Simply by calling theexecutemethod,crspopulates itself with the requested data from the tableCUSTOMERS.crs.setCommand("SELECT FIRST_NAME, LAST_NAME, ADDRESS FROM CUSTOMERS" + "WHERE CREDIT_LIMIT > ? AND REGION = ?"); crs.setInt(1, 5000); crs.setString(2, "West"); crs.execute();10.0 Paging Data
Because aCachedRowSetobject stores data in memory, the amount of data that it can contain at any one time is determined by the amount of memory available. To get around this limitation, aCachedRowSetobject can retrieve data from aResultSetobject in chunks of data, called pages. To take advantage of this mechanism, an application sets the number of rows to be included in a page using the methodsetPageSize. In other words, if the page size is set to five, a chunk of five rows of data will be fetched from the data source at one time. An application can also optionally set the maximum number of rows that may be fetched at one time. If the maximum number of rows is set to zero, or no maximum number of rows is set, there is no limit to the number of rows that may be fetched at a time.After properties have been set, the
CachedRowSetobject must be populated with data using either the methodpopulateor the methodexecute. The following lines of code demonstrate using the methodpopulate. Note that this version of the method takes two parameters, aResultSethandle and the row in theResultSetobject from which to start retrieving rows.CachedRowSet crs = new CachedRowSetImpl(); crs.setMaxRows(20); crs.setPageSize(4); crs.populate(rsHandle, 10);When this code runs, crs will be populated with four rows from rsHandle starting with the tenth row.The next code fragment shows populating a
CachedRowSetobject using the methodexecute, which may or may not take aConnectionobject as a parameter. This code passesexecutetheConnectionobject conHandle.Note that there are two differences between the following code fragment and the previous one. First, the method
setMaxRowsis not called, so there is no limit set for the number of rows that crs may contain. (Remember that crs always has the overriding limit of how much data it can store in memory.) The second difference is that the you cannot pass the methodexecutethe number of the row in theResultSetobject from which to start retrieving rows. This method always starts with the first row.CachedRowSet crs = new CachedRowSetImpl(); crs.setPageSize(5); crs.execute(conHandle);After this code has run, crs will contain five rows of data from theResultSetobject produced by the command for crs. The writer for crs will use conHandle to connect to the data source and execute the command for crs. An application is then able to operate on the data in crs in the same way that it would operate on data in any otherCachedRowSetobject.To access the next page (chunk of data), an application calls the method
nextPage. This method creates a newCachedRowSetobject and fills it with the next page of data. For example, assume that theCachedRowSetobject's command returns aResultSetobject rs with 1000 rows of data. If the page size has been set to 100, the first call to the methodnextPagewill create aCachedRowSetobject containing the first 100 rows of rs. After doing what it needs to do with the data in these first 100 rows, the application can again call the methodnextPageto create anotherCachedRowSetobject with the second 100 rows from rs. The data from the firstCachedRowSetobject will no longer be in memory because it is replaced with the data from the secondCachedRowSetobject. After the tenth call to the methodnextPage, the tenthCachedRowSetobject will contain the last 100 rows of data from rs, which are stored in memory. At any given time, the data from only oneCachedRowSetobject is stored in memory.The method
nextPagereturnstrueas long as the current page is not the last page of rows andfalsewhen there are no more pages. It can therefore be used in awhileloop to retrieve all of the pages, as is demonstrated in the following lines of code.CachedRowSet crs = CachedRowSetImpl(); crs.setPageSize(100); crs.execute(conHandle); while(crs.nextPage()) { while(crs.next()) { . . . // operate on chunks (of 100 rows each) in crs, // row by row } }After this code fragment has been run, the application will have traversed all 1000 rows, but it will have had no more than 100 rows in memory at a time.The
CachedRowSetinterface also defines the methodpreviousPage. Just as the methodnextPageis analogous to theResultSetmethodnext, the methodpreviousPageis analogous to theResultSetmethodprevious. Similar to the methodnextPage,previousPagecreates aCachedRowSetobject containing the number of rows set as the page size. So, for instance, the methodpreviousPagecould be used in awhileloop at the end of the preceding code fragment to navigate back through the pages from the last page to the first page. The methodpreviousPageis also similar tonextPagein that it can be used in awhileloop, except that it returnstrueas long as there is another page preceding it andfalsewhen there are no more pages ahead of it.By positioning the cursor after the last row for each page, as is done in the following code fragment, the method
previousnavigates from the last row to the first row in each page. The code could also have left the cursor before the first row on each page and then used the methodnextin awhileloop to navigate each page from the first row to the last row.The following code fragment assumes a continuation from the previous code fragment, meaning that the cursor for the tenth
CachedRowSetobject is on the last row. The code moves the cursor to after the last row so that the first call to the methodpreviouswill put the cursor back on the last row. After going through all of the rows in the last page (theCachedRowSetobject crs), the code then enters thewhileloop to get to the ninth page, go through the rows backwards, go to the eighth page, go through the rows backwards, and so on to the first row of the first page.crs.afterLast(); while(crs.previous()) { . . . // navigate through the rows, last to first { while(crs.previousPage()) { crs.afterLast(); while(crs.previous()) { . . . // go from the last row to the first row of each page } }- Since:
- 1.5
-
-
Field Summary
Fields Modifier and Type Field Description static booleanCOMMIT_ON_ACCEPT_CHANGESDeprecated.Because this field is final (it is part of an interface), its value cannot be changed.-
Fields declared in interface java.sql.ResultSet
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
-
-
Method Summary
All Methods Instance Methods Abstract Methods Modifier and Type Method Description voidacceptChanges()Propagates row update, insert and delete changes made to thisCachedRowSetobject to the underlying data source.voidacceptChanges(Connection con)Propagates all row update, insert and delete changes to the data source backing thisCachedRowSetobject using the specifiedConnectionobject to establish a connection to the data source.booleancolumnUpdated(int idx)Indicates whether the designated column in the current row of thisCachedRowSetobject has been updated.booleancolumnUpdated(String columnName)Indicates whether the designated column in the current row of thisCachedRowSetobject has been updated.voidcommit()EachCachedRowSetobject'sSyncProvidercontains aConnectionobject from theResultSetor JDBC properties passed to it's constructors.CachedRowSetcreateCopy()Creates aRowSetobject that is a deep copy of the data in thisCachedRowSetobject.CachedRowSetcreateCopyNoConstraints()Creates aCachedRowSetobject that is a deep copy of thisCachedRowSetobject's data but is independent of it.CachedRowSetcreateCopySchema()Creates aCachedRowSetobject that is an empty copy of thisCachedRowSetobject.RowSetcreateShared()Returns a newRowSetobject backed by the same data as that of thisCachedRowSetobject.voidexecute(Connection conn)Populates thisCachedRowSetobject with data, using the given connection to produce the result set from which the data will be read.int[]getKeyColumns()Returns an array containing one or more column numbers indicating the columns that form a key that uniquely identifies a row in thisCachedRowSetobject.ResultSetgetOriginal()Returns aResultSetobject containing the original value of thisCachedRowSetobject.ResultSetgetOriginalRow()Returns aResultSetobject containing the original value for the current row only of thisCachedRowSetobject.intgetPageSize()Returns the page-size for theCachedRowSetobjectRowSetWarninggetRowSetWarnings()Retrieves the first warning reported by calls on thisRowSetobject.booleangetShowDeleted()Retrieves abooleanindicating whether rows marked for deletion appear in the set of current rows.SyncProvidergetSyncProvider()Retrieves theSyncProviderimplementation for thisCachedRowSetobject.StringgetTableName()Returns an identifier for the object (table) that was used to create thisCachedRowSetobject.booleannextPage()Increments the current page of theCachedRowSet.voidpopulate(ResultSet data)Populates thisCachedRowSetobject with data from the givenResultSetobject.voidpopulate(ResultSet rs, int startRow)Populates thisCachedRowSetobject with data from the givenResultSetobject.booleanpreviousPage()Decrements the current page of theCachedRowSet.voidrelease()Releases the current contents of thisCachedRowSetobject and sends arowSetChangedevent to all registered listeners.voidrestoreOriginal()Restores thisCachedRowSetobject to its original value, that is, its value before the last set of changes.voidrollback()EachCachedRowSetobject'sSyncProvidercontains aConnectionobject from the originalResultSetor JDBC properties passed to it.voidrollback(Savepoint s)EachCachedRowSetobject'sSyncProvidercontains aConnectionobject from the originalResultSetor JDBC properties passed to it.voidrowSetPopulated(RowSetEvent event, int numRows)Notifies registered listeners that a RowSet object in the given RowSetEvent object has populated a number of additional rows.voidsetKeyColumns(int[] keys)Sets thisCachedRowSetobject'skeyColsfield with the given array of column numbers, which forms a key for uniquely identifying a row in thisCachedRowSetobject.voidsetMetaData(RowSetMetaData md)Sets the metadata for thisCachedRowSetobject with the givenRowSetMetaDataobject.voidsetOriginalRow()Sets the current row in thisCachedRowSetobject as the original row.voidsetPageSize(int size)Sets theCachedRowSetobject's page-size.voidsetShowDeleted(boolean b)Sets the propertyshowDeletedto the givenbooleanvalue, which determines whether rows marked for deletion appear in the set of current rows.voidsetSyncProvider(String provider)Sets theSyncProviderobject for thisCachedRowSetobject to the one specified.voidsetTableName(String tabName)Sets the identifier for the table from which thisCachedRowSetobject was derived to the given table name.intsize()Returns the number of rows in thisCachedRowSetobject.Collection<?>toCollection()Converts thisCachedRowSetobject to aCollectionobject that contains all of thisCachedRowSetobject's data.Collection<?>toCollection(int column)Converts the designated column in thisCachedRowSetobject to aCollectionobject.Collection<?>toCollection(String column)Converts the designated column in thisCachedRowSetobject to aCollectionobject.voidundoDelete()Cancels the deletion of the current row and notifies listeners that a row has changed.voidundoInsert()Immediately removes the current row from thisCachedRowSetobject if the row has been inserted, and also notifies listeners that a row has changed.voidundoUpdate()Immediately reverses the last update operation if the row has been modified.-
Methods declared in interface javax.sql.rowset.Joinable
getMatchColumnIndexes, getMatchColumnNames, setMatchColumn, setMatchColumn, setMatchColumn, setMatchColumn, unsetMatchColumn, unsetMatchColumn, unsetMatchColumn, unsetMatchColumn
-
Methods declared in interface java.sql.ResultSet
absolute, 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, wasNull
-
Methods declared in interface javax.sql.RowSet
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, setUsername
-
Methods declared in interface java.sql.Wrapper
isWrapperFor, unwrap
-
-
-
-
Field Detail
-
COMMIT_ON_ACCEPT_CHANGES
@Deprecated static final boolean COMMIT_ON_ACCEPT_CHANGES
Deprecated.Because this field is final (it is part of an interface), its value cannot be changed.Causes theCachedRowSetobject'sSyncProviderto commit the changes whenacceptChanges()is called. If set to false, the changes will not be committed until one of theCachedRowSetinterface transaction methods is called.- See Also:
commit(),rollback(), Constant Field Values
-
-
Method Detail
-
populate
void populate(ResultSet data) throws SQLException
Populates thisCachedRowSetobject with data from the givenResultSetobject.This method can be used as an alternative to the
executemethod when an application has a connection to an openResultSetobject. Using the methodpopulatecan be more efficient than using the version of theexecutemethod that takes no parameters because it does not open a new connection and re-execute thisCachedRowSetobject's command. Using thepopulatemethod is more a matter of convenience when compared to using the version ofexecutethat takes aResultSetobject.- Parameters:
data- theResultSetobject containing the data to be read into thisCachedRowSetobject- Throws:
SQLException- if a nullResultSetobject is supplied or thisCachedRowSetobject cannot retrieve the associatedResultSetMetaDataobject- See Also:
execute(java.sql.Connection),ResultSet,ResultSetMetaData
-
execute
void execute(Connection conn) throws SQLException
Populates thisCachedRowSetobject with data, using the given connection to produce the result set from which the data will be read. This method should close any database connections that it creates to ensure that thisCachedRowSetobject is disconnected except when it is reading data from its data source or writing data to its data source.The reader for this
CachedRowSetobject will use conn to establish a connection to the data source so that it can execute the rowset's command and read data from the the resultingResultSetobject into thisCachedRowSetobject. This method also closes conn after it has populated thisCachedRowSetobject.If this method is called when an implementation has already been populated, the contents and the metadata are (re)set. Also, if this method is called before the method
acceptChangeshas been called to commit outstanding updates, those updates are lost.- Parameters:
conn- a standard JDBCConnectionobject with valid properties- Throws:
SQLException- if an invalidConnectionobject is supplied or an error occurs in establishing the connection to the data source- See Also:
populate(java.sql.ResultSet),Connection
-
acceptChanges
void acceptChanges() throws SyncProviderExceptionPropagates row update, insert and delete changes made to thisCachedRowSetobject to the underlying data source.This method calls on this
CachedRowSetobject's writer to do the work behind the scenes. StandardCachedRowSetimplementations should use theSyncFactorysingleton to obtain aSyncProviderinstance providing aRowSetWriterobject (writer). The writer will attempt to propagate changes made in thisCachedRowSetobject back to the data source.When the method
acceptChangesexecutes successfully, in addition to writing changes to the data source, it makes the values in the current row be the values in the original row.Depending on the synchronization level of the
SyncProviderimplementation being used, the writer will compare the original values with those in the data source to check for conflicts. When there is a conflict, theRIOptimisticProviderimplementation, for example, throws aSyncProviderExceptionand does not write anything to the data source.An application may choose to catch the
SyncProviderExceptionobject and retrieve theSyncResolverobject it contains. TheSyncResolverobject lists the conflicts row by row and sets a lock on the data source to avoid further conflicts while the current conflicts are being resolved. Further, for each conflict, it provides methods for examining the conflict and setting the value that should be persisted in the data source. After all conflicts have been resolved, an application must call theacceptChangesmethod again to write resolved values to the data source. If all of the values in the data source are already the values to be persisted, the methodacceptChangesdoes nothing.Some provider implementations may use locks to ensure that there are no conflicts. In such cases, it is guaranteed that the writer will succeed in writing changes to the data source when the method
acceptChangesis called. This method may be called immediately after the methodsupdateRow,insertRow, ordeleteRowhave been called, but it is more efficient to call it only once after all changes have been made so that only one connection needs to be established.Note: The
acceptChanges()method will determine if theCOMMIT_ON_ACCEPT_CHANGESis set to true or not. If it is set to true, all updates in the synchronization are committed to the data source. Otherwise, the application must explicitly call thecommit()orrollback()methods as appropriate.- Throws:
SyncProviderException- if the underlying synchronization provider's writer fails to write the updates back to the data source- See Also:
acceptChanges(java.sql.Connection),RowSetWriter,SyncFactory,SyncProvider,SyncProviderException,SyncResolver
-
acceptChanges
void acceptChanges(Connection con) throws SyncProviderException
Propagates all row update, insert and delete changes to the data source backing thisCachedRowSetobject using the specifiedConnectionobject to establish a connection to the data source.The other version of the
acceptChangesmethod is not passed a connection because it uses theConnectionobject already defined within theRowSetobject, which is the connection used for populating it initially.This form of the method
acceptChangesis similar to the form that takes no arguments; however, unlike the other form, this form can be used only when the underlying data source is a JDBC data source. The updatedConnectionproperties must be used by theSyncProviderto reset theRowSetWriterconfiguration to ensure that the contents of theCachedRowSetobject are synchronized correctly.When the method
acceptChangesexecutes successfully, in addition to writing changes to the data source, it makes the values in the current row be the values in the original row.Depending on the synchronization level of the
SyncProviderimplementation being used, the writer will compare the original values with those in the data source to check for conflicts. When there is a conflict, theRIOptimisticProviderimplementation, for example, throws aSyncProviderExceptionand does not write anything to the data source.An application may choose to catch the
SyncProviderExceptionobject and retrieve theSyncResolverobject it contains. TheSyncResolverobject lists the conflicts row by row and sets a lock on the data source to avoid further conflicts while the current conflicts are being resolved. Further, for each conflict, it provides methods for examining the conflict and setting the value that should be persisted in the data source. After all conflicts have been resolved, an application must call theacceptChangesmethod again to write resolved values to the data source. If all of the values in the data source are already the values to be persisted, the methodacceptChangesdoes nothing.Some provider implementations may use locks to ensure that there are no conflicts. In such cases, it is guaranteed that the writer will succeed in writing changes to the data source when the method
acceptChangesis called. This method may be called immediately after the methodsupdateRow,insertRow, ordeleteRowhave been called, but it is more efficient to call it only once after all changes have been made so that only one connection needs to be established.Note: The
acceptChanges()method will determine if theCOMMIT_ON_ACCEPT_CHANGESis set to true or not. If it is set to true, all updates in the synchronization are committed to the data source. Otherwise, the application must explicitly call thecommitorrollbackmethods as appropriate.- Parameters:
con- a standard JDBCConnectionobject- Throws:
SyncProviderException- if the underlying synchronization provider's writer fails to write the updates back to the data source- See Also:
acceptChanges(),RowSetWriter,SyncFactory,SyncProvider,SyncProviderException,SyncResolver
-
restoreOriginal
void restoreOriginal() throws SQLExceptionRestores thisCachedRowSetobject to its original value, that is, its value before the last set of changes. If there have been no changes to the rowset or only one set of changes, the original value is the value with which thisCachedRowSetobject was populated; otherwise, the original value is the value it had immediately before its current value.When this method is called, a
CachedRowSetimplementation must ensure that all updates, inserts, and deletes to the current rowset instance are replaced by the previous values. In addition, the cursor should be reset to the first row and arowSetChangedevent should be fired to notify all registered listeners.- Throws:
SQLException- if an error occurs rolling back the current value of thisCachedRowSetobject to its previous value- See Also:
RowSetListener.rowSetChanged(javax.sql.RowSetEvent)
-
release
void release() throws SQLExceptionReleases the current contents of thisCachedRowSetobject and sends arowSetChangedevent to all registered listeners. Any outstanding updates are discarded and the rowset contains no rows after this method is called. There are no interactions with the underlying data source, and any rowset content, metadata, and content updates should be non-recoverable.This
CachedRowSetobject should lock until its contents and associated updates are fully cleared, thus preventing 'dirty' reads by other components that hold a reference to thisRowSetobject. In addition, the contents cannot be released until all components reading thisCachedRowSetobject have completed their reads. ThisCachedRowSetobject should be returned to normal behavior after firing therowSetChangedevent.The metadata, including JDBC properties and Synchronization SPI properties, are maintained for future use. It is important that properties such as the
commandproperty be relevant to the originating data source from which thisCachedRowSetobject was originally established.This method empties a rowset, as opposed to the
closemethod, which marks the entire rowset as recoverable to allow the garbage collector the rowset's Java VM resources.- Throws:
SQLException- if an error occurs flushing the contents of thisCachedRowSetobject- See Also:
RowSetListener.rowSetChanged(javax.sql.RowSetEvent),ResultSet.close()
-
undoDelete
void undoDelete() throws SQLExceptionCancels the deletion of the current row and notifies listeners that a row has changed. After this method is called, the current row is no longer marked for deletion. This method can be called at any time during the lifetime of the rowset.In addition, multiple cancellations of row deletions can be made by adjusting the position of the cursor using any of the cursor position control methods such as:
CachedRowSet.absoluteCachedRowSet.firstCachedRowSet.last
- Throws:
SQLException- if (1) the current row has not been deleted or (2) the cursor is on the insert row, before the first row, or after the last row- See Also:
undoInsert(),ResultSet.cancelRowUpdates()
-
undoInsert
void undoInsert() throws SQLExceptionImmediately removes the current row from thisCachedRowSetobject if the row has been inserted, and also notifies listeners that a row has changed. This method can be called at any time during the lifetime of a rowset and assuming the current row is within the exception limitations (see below), it cancels the row insertion of the current row.In addition, multiple cancellations of row insertions can be made by adjusting the position of the cursor using any of the cursor position control methods such as:
CachedRowSet.absoluteCachedRowSet.firstCachedRowSet.last
- Throws:
SQLException- if (1) the current row has not been inserted or (2) the cursor is before the first row, after the last row, or on the insert row- See Also:
undoDelete(),ResultSet.cancelRowUpdates()
-
undoUpdate
void undoUpdate() throws SQLExceptionImmediately reverses the last update operation if the row has been modified. This method can be called to reverse updates on all columns until all updates in a row have been rolled back to their state just prior to the last synchronization (acceptChanges) or population. This method may also be called while performing updates to the insert row.undoUpdatemay be called at any time during the lifetime of a rowset; however, after a synchronization has occurred, this method has no effect until further modification to the rowset data has occurred.- Throws:
SQLException- if the cursor is before the first row or after the last row in thisCachedRowSetobject- See Also:
undoDelete(),undoInsert(),ResultSet.cancelRowUpdates()
-
columnUpdated
boolean columnUpdated(int idx) throws SQLExceptionIndicates whether the designated column in the current row of thisCachedRowSetobject has been updated.- Parameters:
idx- anintidentifying the column to be checked for updates- Returns:
trueif the designated column has been visibly updated;falseotherwise- Throws:
SQLException- if the cursor is on the insert row, before the first row, or after the last row- See Also:
DatabaseMetaData.updatesAreDetected(int)
-
columnUpdated
boolean columnUpdated(String columnName) throws SQLException
Indicates whether the designated column in the current row of thisCachedRowSetobject has been updated.- Parameters:
columnName- aStringobject giving the name of the column to be checked for updates- Returns:
trueif the column has been visibly updated;falseotherwise- Throws:
SQLException- if the cursor is on the insert row, before the first row, or after the last row- See Also:
DatabaseMetaData.updatesAreDetected(int)
-
toCollection
Collection<?> toCollection() throws SQLException
Converts thisCachedRowSetobject to aCollectionobject that contains all of thisCachedRowSetobject's data. Implementations have some latitude in how they can represent thisCollectionobject because of the abstract nature of theCollectionframework. Each row must be fully represented in either a general purposeCollectionimplementation or a specializedCollectionimplementation, such as aTreeMapobject or aVectorobject. An SQLNULLcolumn value must be represented as anullin the Java programming language.The standard reference implementation for the
CachedRowSetinterface uses aTreeMapobject for the rowset, with the values in each row being contained inVectorobjects. It is expected that most implementations will do the same.The
TreeMaptype of collection guarantees that the map will be in ascending key order, sorted according to the natural order for the key's class. Each key references aVectorobject that corresponds to one row of aRowSetobject. Therefore, the size of eachVectorobject must be exactly equal to the number of columns in theRowSetobject. The key used by theTreeMapcollection is determined by the implementation, which may choose to leverage a set key that is available within the internalRowSettabular structure by virtue of a key already set either on theRowSetobject itself or on the underlying SQL data.- Returns:
- a
Collectionobject that contains the values in each row in thisCachedRowSetobject - Throws:
SQLException- if an error occurs generating the collection- See Also:
toCollection(int),toCollection(String)
-
toCollection
Collection<?> toCollection(int column) throws SQLException
Converts the designated column in thisCachedRowSetobject to aCollectionobject. Implementations have some latitude in how they can represent thisCollectionobject because of the abstract nature of theCollectionframework. Each column value should be fully represented in either a general purposeCollectionimplementation or a specializedCollectionimplementation, such as aVectorobject. An SQLNULLcolumn value must be represented as anullin the Java programming language.The standard reference implementation uses a
Vectorobject to contain the column values, and it is expected that most implementations will do the same. If aVectorobject is used, it size must be exactly equal to the number of rows in thisCachedRowSetobject.- Parameters:
column- anintindicating the column whose values are to be represented in aCollectionobject- Returns:
- a
Collectionobject that contains the values stored in the specified column of thisCachedRowSetobject - Throws:
SQLException- if an error occurs generating the collection or an invalid column id is provided- See Also:
toCollection(),toCollection(String)
-
toCollection
Collection<?> toCollection(String column) throws SQLException
Converts the designated column in thisCachedRowSetobject to aCollectionobject. Implementations have some latitude in how they can represent thisCollectionobject because of the abstract nature of theCollectionframework. Each column value should be fully represented in either a general purposeCollectionimplementation or a specializedCollectionimplementation, such as aVectorobject. An SQLNULLcolumn value must be represented as anullin the Java programming language.The standard reference implementation uses a
Vectorobject to contain the column values, and it is expected that most implementations will do the same. If aVectorobject is used, it size must be exactly equal to the number of rows in thisCachedRowSetobject.- Parameters:
column- aStringobject giving the name of the column whose values are to be represented in a collection- Returns:
- a
Collectionobject that contains the values stored in the specified column of thisCachedRowSetobject - Throws:
SQLException- if an error occurs generating the collection or an invalid column id is provided- See Also:
toCollection(),toCollection(int)
-
getSyncProvider
SyncProvider getSyncProvider() throws SQLException
Retrieves theSyncProviderimplementation for thisCachedRowSetobject. Internally, this method is used by a rowset to trigger read or write actions between the rowset and the data source. For example, a rowset may need to get a handle on the rowset reader (RowSetReaderobject) from theSyncProviderto allow the rowset to be populated.RowSetReader rowsetReader = null; SyncProvider provider = SyncFactory.getInstance("javax.sql.rowset.provider.RIOptimisticProvider"); if (provider instanceof RIOptimisticProvider) { rowsetReader = provider.getRowSetReader(); }Assuming rowsetReader is a private, accessible field within the rowset implementation, when an application calls theexecutemethod, it in turn calls on the reader'sreadDatamethod to populate theRowSetobject.rowsetReader.readData((RowSetInternal)this);In addition, an application can use the
SyncProviderobject returned by this method to call methods that return information about theSyncProviderobject, including information about the vendor, version, provider identification, synchronization grade, and locks it currently has set.- Returns:
- the
SyncProviderobject that was set when the rowset was instantiated, or if none was set, the default provider - Throws:
SQLException- if an error occurs while returning theSyncProviderobject- See Also:
setSyncProvider(java.lang.String)
-
setSyncProvider
void setSyncProvider(String provider) throws SQLException
Sets theSyncProviderobject for thisCachedRowSetobject to the one specified. This method allows theSyncProviderobject to be reset.A
CachedRowSetimplementation should always be instantiated with an availableSyncProvidermechanism, but there are cases where resetting theSyncProviderobject is desirable or necessary. For example, an application might want to use the defaultSyncProviderobject for a time and then choose to use a provider that has more recently become available and better fits its needs.Resetting the
SyncProviderobject causes theRowSetobject to request a newSyncProviderimplementation from theSyncFactory. This has the effect of resetting all previous connections and relationships with the originating data source and can potentially drastically change the synchronization behavior of a disconnected rowset.- Parameters:
provider- aStringobject giving the fully qualified class name of aSyncProviderimplementation- Throws:
SQLException- if an error occurs while attempting to reset theSyncProviderimplementation- See Also:
getSyncProvider()
-
size
int size()
Returns the number of rows in thisCachedRowSetobject.- Returns:
- number of rows in the rowset
-
setMetaData
void setMetaData(RowSetMetaData md) throws SQLException
Sets the metadata for thisCachedRowSetobject with the givenRowSetMetaDataobject. When aRowSetReaderobject is reading the contents of a rowset, it creates aRowSetMetaDataobject and initializes it using the methods in theRowSetMetaDataimplementation. The reference implementation uses theRowSetMetaDataImplclass. When the reader has completed reading the rowset contents, this method is called internally to pass theRowSetMetaDataobject to the rowset.- Parameters:
md- aRowSetMetaDataobject containing metadata about the columns in thisCachedRowSetobject- Throws:
SQLException- if invalid metadata is supplied to the rowset
-
getOriginal
ResultSet getOriginal() throws SQLException
Returns aResultSetobject containing the original value of thisCachedRowSetobject.The cursor for the
ResultSetobject should be positioned before the first row. In addition, the returnedResultSetobject should have the following properties:- ResultSet.TYPE_SCROLL_INSENSITIVE
- ResultSet.CONCUR_UPDATABLE
The original value for a
RowSetobject is the value it had before the last synchronization with the underlying data source. If there have been no synchronizations, the original value will be the value with which theRowSetobject was populated. This method is called internally when an application calls the methodacceptChangesand theSyncProviderobject has been implemented to check for conflicts. If this is the case, the writer compares the original value with the value currently in the data source to check for conflicts.- Returns:
- a
ResultSetobject that contains the original value for thisCachedRowSetobject - Throws:
SQLException- if an error occurs producing theResultSetobject
-
getOriginalRow
ResultSet getOriginalRow() throws SQLException
Returns aResultSetobject containing the original value for the current row only of thisCachedRowSetobject.The cursor for the
ResultSetobject should be positioned before the first row. In addition, the returnedResultSetobject should have the following properties:- ResultSet.TYPE_SCROLL_INSENSITIVE
- ResultSet.CONCUR_UPDATABLE
- Returns:
- the original result set of the row
- Throws:
SQLException- if there is no current row- See Also:
setOriginalRow()
-
setOriginalRow
void setOriginalRow() throws SQLExceptionSets the current row in thisCachedRowSetobject as the original row.This method is called internally after the any modified values in the current row have been synchronized with the data source. The current row must be tagged as no longer inserted, deleted or updated.
A call to
setOriginalRowis irreversible.- Throws:
SQLException- if there is no current row or an error is encountered resetting the contents of the original row- See Also:
getOriginalRow()
-
getTableName
String getTableName() throws SQLException
Returns an identifier for the object (table) that was used to create thisCachedRowSetobject. This name may be set on multiple occasions, and the specification imposes no limits on how many times this may occur or whether standard implementations should keep track of previous table names.- Returns:
- a
Stringobject giving the name of the table that is the source of data for thisCachedRowSetobject ornullif no name has been set for the table - Throws:
SQLException- if an error is encountered returning the table name- See Also:
ResultSetMetaData.getTableName(int)
-
setTableName
void setTableName(String tabName) throws SQLException
Sets the identifier for the table from which thisCachedRowSetobject was derived to the given table name. The writer uses this name to determine which table to use when comparing the values in the data source with theCachedRowSetobject's values during a synchronization attempt. The table identifier also indicates where modified values from thisCachedRowSetobject should be written.The implementation of this
CachedRowSetobject may obtain the the name internally from theRowSetMetaDataImplobject.- Parameters:
tabName- aStringobject identifying the table from which thisCachedRowSetobject was derived; cannot benullbut may be an empty string- Throws:
SQLException- if an error is encountered naming the table or tabName isnull- See Also:
RowSetMetaData.setTableName(int, java.lang.String),RowSetWriter,SyncProvider
-
getKeyColumns
int[] getKeyColumns() throws SQLExceptionReturns an array containing one or more column numbers indicating the columns that form a key that uniquely identifies a row in thisCachedRowSetobject.- Returns:
- an array containing the column number or numbers that indicate which columns
constitute a primary key
for a row in this
CachedRowSetobject. This array should be empty if no columns are representative of a primary key. - Throws:
SQLException- if thisCachedRowSetobject is empty- See Also:
setKeyColumns(int[]),Joinable.getMatchColumnIndexes(),Joinable.getMatchColumnNames()
-
setKeyColumns
void setKeyColumns(int[] keys) throws SQLExceptionSets thisCachedRowSetobject'skeyColsfield with the given array of column numbers, which forms a key for uniquely identifying a row in thisCachedRowSetobject.If a
CachedRowSetobject becomes part of aJoinRowSetobject, the keys defined by this method and the resulting constraints are maintained if the columns designated as key columns also become match columns.- Parameters:
keys- an array ofintindicating the columns that form a primary key for thisCachedRowSetobject; every element in the array must be greater than0and less than or equal to the number of columns in this rowset- Throws:
SQLException- if any of the numbers in the given array are not valid for this rowset- See Also:
getKeyColumns(),Joinable.setMatchColumn(String),Joinable.setMatchColumn(int)
-
createShared
RowSet createShared() throws SQLException
Returns a newRowSetobject backed by the same data as that of thisCachedRowSetobject. In effect, bothCachedRowSetobjects have a cursor over the same data. As a result, any changes made by a duplicate are visible to the original and to any other duplicates, just as a change made by the original is visible to all of its duplicates. If a duplicate calls a method that changes the underlying data, the method it calls notifies all registered listeners just as it would when it is called by the originalCachedRowSetobject.In addition, any
RowSetobject created by this method will have the same properties as thisCachedRowSetobject. For example, if thisCachedRowSetobject is read-only, all of its duplicates will also be read-only. If it is changed to be updatable, the duplicates also become updatable.NOTE: If multiple threads access
RowSetobjects created from thecreateShared()method, the following behavior is specified to preserve shared data integrity: reads and writes of all sharedRowSetobjects should be made serially between each object and the single underlying tabular structure.- Returns:
- a new shared
RowSetobject that has the same properties as thisCachedRowSetobject and that has a cursor over the same data - Throws:
SQLException- if an error occurs or cloning is not supported in the underlying platform- See Also:
RowSetEvent,RowSetListener
-
createCopy
CachedRowSet createCopy() throws SQLException
Creates aRowSetobject that is a deep copy of the data in thisCachedRowSetobject. In contrast to theRowSetobject generated from acreateSharedcall, updates made to the copy of the originalRowSetobject must not be visible to the originalRowSetobject. Also, any event listeners that are registered with the originalRowSetmust not have scope over the newRowSetcopies. In addition, any constraint restrictions established must be maintained.- Returns:
- a new
RowSetobject that is a deep copy of thisCachedRowSetobject and is completely independent of thisCachedRowSetobject - Throws:
SQLException- if an error occurs in generating the copy of the of thisCachedRowSetobject- See Also:
createShared(),createCopySchema(),createCopyNoConstraints(),RowSetEvent,RowSetListener
-
createCopySchema
CachedRowSet createCopySchema() throws SQLException
Creates aCachedRowSetobject that is an empty copy of thisCachedRowSetobject. The copy must not contain any contents but only represent the table structure of the originalCachedRowSetobject. In addition, primary or foreign key constraints set in the originatingCachedRowSetobject must be equally enforced in the new emptyCachedRowSetobject. In contrast to theRowSetobject generated from acreateSharedmethod call, updates made to a copy of thisCachedRowSetobject with thecreateCopySchemamethod must not be visible to it.Applications can form a
WebRowSetobject from theCachedRowSetobject returned by this method in order to export theRowSetschema definition to XML for future use.- Returns:
- An empty copy of this
CachedRowSetobject - Throws:
SQLException- if an error occurs in cloning the structure of thisCachedRowSetobject- See Also:
createShared(),createCopySchema(),createCopyNoConstraints(),RowSetEvent,RowSetListener
-
createCopyNoConstraints
CachedRowSet createCopyNoConstraints() throws SQLException
Creates aCachedRowSetobject that is a deep copy of thisCachedRowSetobject's data but is independent of it. In contrast to theRowSetobject generated from acreateSharedmethod call, updates made to a copy of thisCachedRowSetobject must not be visible to it. Also, any event listeners that are registered with thisCachedRowSetobject must not have scope over the newRowSetobject. In addition, any constraint restrictions established for thisCachedRowSetobject must not be maintained in the copy.- Returns:
- a new
CachedRowSetobject that is a deep copy of thisCachedRowSetobject and is completely independent of thisCachedRowSetobject - Throws:
SQLException- if an error occurs in generating the copy of the of thisCachedRowSetobject- See Also:
createCopy(),createShared(),createCopySchema(),RowSetEvent,RowSetListener
-
getRowSetWarnings
RowSetWarning getRowSetWarnings() throws SQLException
Retrieves the first warning reported by calls on thisRowSetobject. Subsequent warnings on thisRowSetobject will be chained to theRowSetWarningobject that this method returns. The warning chain is automatically cleared each time a new row is read. This method may not be called on a RowSet object that has been closed; doing so will cause aSQLExceptionto be thrown.- Returns:
- RowSetWarning the first
RowSetWarningobject reported or null if there are none - Throws:
SQLException- if this method is called on a closed RowSet- See Also:
RowSetWarning
-
getShowDeleted
boolean getShowDeleted() throws SQLExceptionRetrieves abooleanindicating whether rows marked for deletion appear in the set of current rows. Iftrueis returned, deleted rows are visible with the current rows. Iffalseis returned, rows are not visible with the set of current rows. The default value isfalse.Standard rowset implementations may choose to restrict this behavior due to security considerations or to better fit certain deployment scenarios. This is left as implementation defined and does not represent standard behavior.
Note: Allowing deleted rows to remain visible complicates the behavior of some standard JDBC
RowSetImplementations methods. However, most rowset users can simply ignore this extra detail because only very specialized applications will likely want to take advantage of this feature.- Returns:
trueif deleted rows are visible;falseotherwise- Throws:
SQLException- if a rowset implementation is unable to to determine whether rows marked for deletion are visible- See Also:
setShowDeleted(boolean)
-
setShowDeleted
void setShowDeleted(boolean b) throws SQLExceptionSets the propertyshowDeletedto the givenbooleanvalue, which determines whether rows marked for deletion appear in the set of current rows. If the value is set totrue, deleted rows are immediately visible with the set of current rows. If the value is set tofalse, the deleted rows are set as invisible with the current set of rows.Standard rowset implementations may choose to restrict this behavior due to security considerations or to better fit certain deployment scenarios. This is left as implementations defined and does not represent standard behavior.
- Parameters:
b-trueif deleted rows should be shown;falseotherwise- Throws:
SQLException- if a rowset implementation is unable to to reset whether deleted rows should be visible- See Also:
getShowDeleted()
-
commit
void commit() throws SQLExceptionEachCachedRowSetobject'sSyncProvidercontains aConnectionobject from theResultSetor JDBC properties passed to it's constructors. This method wraps theConnectioncommit method to allow flexible auto commit or non auto commit transactional control support.Makes all changes that are performed by the
acceptChanges()method since the previous commit/rollback permanent. This method should be used only when auto-commit mode has been disabled.- Throws:
SQLException- if a database access error occurs or this Connection object within thisCachedRowSetis in auto-commit mode- See Also:
Connection.setAutoCommit(boolean)
-
rollback
void rollback() throws SQLExceptionEachCachedRowSetobject'sSyncProvidercontains aConnectionobject from the originalResultSetor JDBC properties passed to it.Undoes all changes made in the current transaction. This method should be used only when auto-commit mode has been disabled.
- Throws:
SQLException- if a database access error occurs or this Connection object within thisCachedRowSetis in auto-commit mode.
-
rollback
void rollback(Savepoint s) throws SQLException
EachCachedRowSetobject'sSyncProvidercontains aConnectionobject from the originalResultSetor JDBC properties passed to it.Undoes all changes made in the current transaction back to the last
Savepointtransaction marker. This method should be used only when auto-commit mode has been disabled.- Parameters:
s- ASavepointtransaction marker- Throws:
SQLException- if a database access error occurs or this Connection object within thisCachedRowSetis in auto-commit mode.
-
rowSetPopulated
void rowSetPopulated(RowSetEvent event, int numRows) throws SQLException
Notifies registered listeners that a RowSet object in the given RowSetEvent object has populated a number of additional rows. ThenumRowsparameter ensures that this event will only be fired everynumRow.The source of the event can be retrieved with the method event.getSource.
- Parameters:
event- aRowSetEventobject that contains theRowSetobject that is the source of the eventsnumRows- when populating, the number of rows interval on which theCachedRowSetpopulated should fire; the default value is zero; cannot be less thanfetchSizeor zero- Throws:
SQLException-numRows < 0 or numRows < getFetchSize()
-
populate
void populate(ResultSet rs, int startRow) throws SQLException
Populates thisCachedRowSetobject with data from the givenResultSetobject. While related to thepopulate(ResultSet)method, an additional parameter is provided to allow starting position within theResultSetfrom where to populate the CachedRowSet instance.This method can be used as an alternative to the
executemethod when an application has a connection to an openResultSetobject. Using the methodpopulatecan be more efficient than using the version of theexecutemethod that takes no parameters because it does not open a new connection and re-execute thisCachedRowSetobject's command. Using thepopulatemethod is more a matter of convenience when compared to using the version ofexecutethat takes aResultSetobject.- Parameters:
startRow- the position in theResultSetfrom where to start populating the records in thisCachedRowSetrs- theResultSetobject containing the data to be read into thisCachedRowSetobject- Throws:
SQLException- if a nullResultSetobject is supplied or thisCachedRowSetobject cannot retrieve the associatedResultSetMetaDataobject- See Also:
execute(java.sql.Connection),populate(ResultSet),ResultSet,ResultSetMetaData
-
setPageSize
void setPageSize(int size) throws SQLExceptionSets theCachedRowSetobject's page-size. ACachedRowSetmay be configured to populate itself in page-size sized batches of rows. When eitherpopulate()orexecute()are called, theCachedRowSetfetches an additional page according to the original SQL query used to populate the RowSet.- Parameters:
size- the page-size of theCachedRowSet- Throws:
SQLException- if an error occurs setting theCachedRowSetpage size or if the page size is less than 0.
-
getPageSize
int getPageSize()
Returns the page-size for theCachedRowSetobject- Returns:
- an
intpage size
-
nextPage
boolean nextPage() throws SQLExceptionIncrements the current page of theCachedRowSet. This causes theCachedRowSetimplementation to fetch the next page-size rows and populate the RowSet, if remaining rows remain within scope of the original SQL query used to populated the RowSet.- Returns:
- true if more pages exist; false if this is the last page
- Throws:
SQLException- if an error occurs fetching the next page, or if this method is called prematurely before populate or execute.
-
previousPage
boolean previousPage() throws SQLExceptionDecrements the current page of theCachedRowSet. This causes theCachedRowSetimplementation to fetch the previous page-size rows and populate the RowSet. The amount of rows returned in the previous page must always remain within scope of the original SQL query used to populate the RowSet.- Returns:
- true if the previous page is successfully retrieved; false if this is the first page.
- Throws:
SQLException- if an error occurs fetching the previous page, or if this method is called prematurely before populate or execute.
-
-