• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is it OK to put Statement and ResultSet in DAO base class?

 
N Carlo
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

In my web application, I have a base class called Dao that contains the following:



Then I have subclasses that extend Dao and inherit the Connection, PreparedStatement, and ResultSet. Here is an example of how they are used:



The reason for doing this is simply that the subclasses always need those variables to do their work, so it seemed sensible to put them in a parent class. Is there any risk or drawback to doing it this way? Is it better to just always declare the Connection, PreparedStatement, and ResultSet as local variables? Thanks for your help.
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I think any PreparedStatement or ResultSet should be local to methods within the DAOs that extend your base class.

Similarly, a Connection object should come from a DataSource which is set on construction of your DAO.
 
N Carlo
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi James,

Thanks for your reply. Can you explain the reason why they should be local variables? What is the danger of putting them in the base class?
 
Kunal Lakhani
Ranch Hand
Posts: 622
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What if i create a separate class for getting and closing connection, and , use PreparedStatement or ResultSet as local to methods within the DAO?
 
Martin Vajsar
Sheriff
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
N Carlo wrote:Hi James,

Thanks for your reply. Can you explain the reason why they should be local variables? What is the danger of putting them in the base class?

I assume you're using a connection pool. In this case, you need to open and close all your database resources as part of servicing every request. This is somewhat obvious for connections, as you want the connection returned to the pool after servicing one request to be available when servicing another request. The other resources have to be closed simply because they are tied to the connection they came from. To reduce the overhead, some connection pools cache these objects (such as PreparedStatements) transparently.

Edit: therefore, you cannot keep these resources open outside of servicing a request, which means they do not belong to the class, but should be declared locally.
 
N Carlo
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, sounds like using local variables is the standard way to do it, so I'll go that route. Thanks for your help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic