Question

I am using Vaadin framework and following MVC design pattern to develop a web application project. While implementing connection pooling feature for my project I encountered the following problem. I am getting the ResultSet in one class(data class) and I am using that ResultSet in another class(Business Logic). I have to close the connection object after using that ResultSet in the business logic class. What may be the efficient way to achieve this without passing the connection object to the business logic class? Please Explain.Thank You.

Was it helpful?

Solution

I would recommend that you write a Dao which returns a List of Business Objects and NOT the resultsets. The connection must be closed in the Dao itself. Below is an example

public class PersonDao {
    private DataSource ds; //add a setter and inject the JDBC resource
    public List<Person> getPersons() {
        List<Person> personList = new ArrayList();
        Connection con;
        PreparedStatement pstmt;
        try {
            con = ds.getConnection(username, password);
            pstmt = con.prepareStatement("SELECT * FROM PERSON");
            ResultSet rs = pstmt.executeQuery(query); 
            //Fetch the resultset, iterate over it and populate the list
            while (rs.next()) {
                Person p = new Person();
                p.setName(rs.getString("name");
                personList.add(p);
            }
        } catch (Exception ex {
            // ... code to handle exceptions
       } finally {
            if (con != null) con.close();
       }

      return personList;
}

If you can use Java 7, you can also use try with resource which would automatically handle the closing of connections for you. If you are not in a position to change the Dao interface, then it is a good idea to write a layer between the Dao and the business layer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top