2

I have a web application that needs a database back-end.
My back-end is really small (max 4 tables) and the SQL operations are not that much.
So I decided that some robust ORM solution is like hitting a moschito with a hummer and I am going just to do a little DAO pattern so that the code is more clean (instead of hitting the db directly with sql commands).

So far it works but I am not sure that I haven't stepped into a pittfall without knowing.
I use Tomcat's connection pool and I expect concurrent access to the database.

My question is related to concurrency and the use of the java sql objects.

Example:

I do the following:

  • do a query
  • get a result set and use that to build an object (dto)
  • building this object I do a new sql query (using the same connection and having the previous resultset open)

Is this correct/safe?

Also can I reuse the same connection in a re-entrant manner?
I assume it is no problem to use it via multiple threads right?

Generally any tips/guide to get in the right track is welcome

Jim
  • 18,826
  • 34
  • 135
  • 254
  • Check http://stackoverflow.com/questions/8049627/dao-and-dependency-injection-advice – jalopaba Feb 08 '12 at 13:18
  • I know how to structure the classes.Details about `Connections` `ResultSets` and `Statement` are of interest to me and pittfalls – Jim Feb 08 '12 at 13:20

1 Answers1

1

Regarding the connections, as long as you use the connection pool you are guaranteeing that each thread takes its own connection, so from that point of wiew, there is no problem in your approach in a multithreaded environment (you can check Is java.sql.Connection thread safe?).

With respect to the ResultSet and the second query you are performing, you must take into account that a ResultSet maintains a cursor pointing to its current row of data. So the key point in your question is if you are using the same "SELECT statement", because of in that case, you could get the same cursor attributes and some problems may arise.

Check ResultSet's javadoc, especially this sentence:

A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.

and How can I avoid ResultSet is closed exception in Java?.

Community
  • 1
  • 1
jalopaba
  • 8,039
  • 2
  • 44
  • 57
  • Interesting.No I am not using the same (by chance) select but good to know this.Thanks! – Jim Feb 08 '12 at 14:27