I have two classes, a server and some clients. The server class make a query to database and retrieve a certain number of rows. The clients request a part of these rows, each one a different part.
In the server class, is better I maintain the result of the query in the ResultSet and transforming in a array of objects when the client class make the request or transforming all in a array of objects 开发者_JAVA技巧and sending him partially when the request occur?
I think that maintain in the ResultSet is more easier to do and control.
The biggest reason to not leave it in the ResultSet is that it doesn't release the connection back to the pool (unless I'm sorely mistaken). As such you end up holding onto resources that should be freed up for other operations.
Actually I'm not sure if I understood your approach. In typical client/server scenarios with persistance layers, a client (1) calls remote method, this (2) triggers a database operation and the service (3) responds with the requested objects.
In your scenario, it looks like the server reads data from a database, caches it and waits for clients to request chunks.
If I got it right, and the server is caching database objects, then it should transform the data from the result set in objects, I'd prefer a collection or a map to store the "rows". A result set is a rather fragile data structure - like some result sets don't support re-reading of set entries (= you can't iterate twice). I'd always take the data from the set and close it as soon as possible.
If you intend to pass the contents of the result set to other classes or methods then it is definitely better to take the data out of the result set and store it in some form of data structure ( array / List etc ). If you do not do this you will start adding dependencies on the java.sql package to classes that really do not need to be involved in database access. It also makes unit testing of those classes / methods much harder.
If the ResultSet is only being used in a very restricted scope ( ie a single method ) then there's no real benefit in unloading it in to a different data structure though.
精彩评论