Martin Melka
Martin Melka

Reputation: 7799

Singleton in JSP, how to properly tidy up on close?

I am just getting started with jsp and my question is this - when I have a singleton class, how do I tidy up after it?

In particular:

public class DBConnection {
  private static Connection connection = null;
  private static Statement statement = null;

  public static ResultSet executeQuery(String query){
    if (connection == null) { /*initConnection*/ }
    if (statement == null) { /*initStatement*/ }

    // do some stuff
  }
}

Now, I use this class in several pages to get results from jdbc. However, I need to eventually call statement.close(); and connection.close(); - when should I call those?

I am using singleton, because it felt wrong to call for connection to a database over and over whenever I needed to make a query.

Upvotes: 1

Views: 1855

Answers (3)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85799

The Connection must be closed always, and after you have executed all your database statements for the desired operations. Two examples:

Case 1: You must show a list of products to user filtered by criteria from database. Solution: get a connection, retrieve a list of products using the filter criteria, close the connection.

Case 2: The client selects some of these products and updates the minimum stock to get an alert and restock them. Solution: get a connection, update all the products, close the connection.

Based on these cases, we can learn lot of things:

  • You can execute more than a single statement while having/maintaining a single connection open.
  • The connection should live only in the block where it is used. It should not live before or after that.
  • Both cases can happen at the same time since they are in a multi threaded environment. So, a single database connection must not be available to be used by two threads at the same time, in order to avoid result problems. For example, user A searches the products that are in category Foo and user B searches the products that are in category Bar, you don't want to show the products in category Bar to user A.
  • From last sentence, each database operation ((or group of similar operations like Case 2) should be handled in an atomic operation. To assure this, the connection must not be stored in a singleton object, instead it must be live only in the method being used.

In consequence:

  • Do not declare the Connection nor the Statement nor the ResultSet nor other JDBC resource as static. It will simply fail. Instead, declare only the Connection as field of your DBConnection class. Let each method decide to handle each Statement (or PreparedStatement) and ResultSet and specific JDBC resources.
  • Since you must close the connection after its usage, then add two more methods: void open() and void close(). These methods will handle the database connection retrieval and closing that connection.
  • Additional, since the DBConnection looks like a wrapper class for Connection class and database connection operations, I would recommend to have at least three more methods: void setAutoCommit(boolean autoCommit), void commit() and void rollback(). These methods will be plain wrappers for Connection#setAutoCommit Connection#close and Connection#rollback respectively.

Then you can use the class in this way:

public List<Product> getProducts(String categoryName) {
    String sql = "SELECT id, name FROM Product WHERE categoryName = ?";
    List<Product> productList = new ArrayList<Product>();
    DBConnection dbConnection = new DBConnection();
    try {
        dbConnection.open();
        ResultSet resultSet = dbConnection.executeSelect(sql, categoryName); //execute select and apply parameters
        //fill productList...
    } catch (Exception e) {
        //always handle your exceptions
        ...
    } finally {
        //don't forget to also close other resources here like ResultSet...
        //always close the connection
        dbConnection.close();
    }
}

Note that in this example the PreparedStatement is not in the getProducts method, it will be a local variable of the executeSelect method.

Additional notes:

  • When working in an application server, you should not open connections naively e.g. using Class.forName("..."), instead use a database connection pool. You can roll on some database connection pooling libraries like C3P0 as explained here: How to establish a connection pool in JDBC?. Or configure one in your application server, as I explain here: Is it a good idea to put jdbc connection code in servlet class?
  • If this is for learning purposes, then roll on your own classes to handle the communication with your database. In real world applications, this is not recommended (doesn't mean you should not do it). Instead, use a database connectivity framework like ORMs e.g. JPA (Java official ORM framework) or Hibernate; there are no ORM frameworks that handles database communication like Spring JDBC and MyBatis. The choice is yours.

More info:

Upvotes: 1

Whome
Whome

Reputation: 10400

Define connection resource in mywebapp/META-INF/context.xml file

<Resource name="jdbc/mydb" auth="Container" type="javax.sql.DataSource" 
    maxActive="10" maxIdle="2" maxWait="20000" 
    driverClassName="com.mysql.jdbc.Driver" 
    username="myuser" password="mypwd" 
    url="jdbc:mysql://localhost:3306/mydb?useUnicode=true&amp;characterEncoding=utf8"
    validationQuery="SELECT 1" />

Create DB.java helper class to minimize code in other parts of app

import java.sql.*;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;

public class DB {

public static Connection createConnection() throws SQLException {
    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mydb");
        return ds.getConnection();
    } catch (SQLException ex) {
        throw ex;
    } catch (Exception ex) {
        SQLException sqex = new SQLException(ex.getMessage());
        sqex.initCause(ex);
        throw sqex;
    }
}

public static void close(ResultSet rs, Statement stmt, Connection conn) {
       if (rs != null) try { rs.close(); } catch (Exception e) { }
       if (stmt != null) try { stmt.close(); } catch (Exception e) { }
       if (conn != null) try { conn.close(); } catch (Exception e) { }
}

public static void close(ResultSet rs, boolean closeStmtAndConn) {
       if (rs==null) return;
       try {
          Statement stmt = rs.getStatement();
          close(rs, stmt, stmt!=null ? stmt.getConnection() : null);
       } catch (Exception ex) { }
}

}

And somewhere in your app DAO code use DB helper.

public List<MyBean> getBeans() throws SQLException {
    List<MyBean> list = new ArrayList<MyBean>();
    ResultSet rs=null;
    try {
        Connection con = DB.createConnection();
        String sql = "Select * from beantable where typeid=?";
        PreparedStatement stmt = con.prepareStatement(sql, Statement.NO_GENERATED_KEYS);
        stmt.setInt(1, 101);
        rs = stmt.executeQuery();
        while(rs.next()
            list.add( createBean(rs) );
    } finally {
        DB.close(rs, true); // or DB.close(rs, stmt, conn);
    }
    return list;
}

private MyBean createBean(ResultSet rs) throws SQLException {
    MyBean bean = new MyBean();
    bean.setId( rs.getLong("id") );
    bean.setName( rs.getString("name" );
    bean.setTypeId( rs.getInt("typeid") );
    return bean;
}

Upvotes: 1

Lee Meador
Lee Meador

Reputation: 12985

I would add two methods to the class:

public static void open() throws SomeException;
public static void close() throws SomeException;

then your calling code looks something like this{

try {
    DBConnection.open();
    ... code to use the connection one or more times ...
} finally {
    DBConnection.close();
}

Wrap all your database calls inside that and it will take care of closing whether there is an exception thrown or not.

Of course, this isn't much different than having a regular class, which I might recommend:

try {
    DBConnection conn = new DBConnection();
    conn.open();

    ... all the code to use the database (but you pass 'conn' around) ...

} finally {
    conn.close();
}

And you might want to look at the java.lang.AutoCloseable and java.io.Closeable to see if that helps you.

2

If you are keeping it open across page loads, there isn't any place to put the try ... finally stuff so you can open it and close it when the servlet closes or the server closes or something like that.

If you are going to leave it open, you need to make sure and add code to verify it doesn't close when you aren't looking. A short network glitch, for example, could close it down. In that case, you need to reopen it when it gets closed. Otherwise, all database access from that point will fail.

You might want to look into the concept of a DataBase Pool. Apache has one -- DBCP. Tomcat has its own that's quite good. Other containers, like JBOSS, WebSphere, WebLogic all have them. There's a couple that can be used with the Spring Framework. What it does is manage one or more database connections. Your code asks it for one and it returns an open one, unless none is available and then it opens one and returns it. You call close when your code gets through with it but it doesn't really close the connection, it just returns it to the pool.

You can usually configure the pool to check for shut down connections and reopen if needed.

Upvotes: 0

Related Questions