簡體   English   中英

使用連接池時在哪里關閉連接?

[英]Where to close the connection while using connection pooling?

我正在使用Vaadin框架並遵循MVC設計模式來開發Web應用程序項目。 在為我的項目實現連接池功能時,遇到以下問題。 我在一個類(數據類)中獲取ResultSet,而在另一類(業務邏輯)中使用該ResultSet。 在業務邏輯類中使用該ResultSet之后,必須關閉連接對象。 在不將連接對象傳遞給業務邏輯類的情況下實現此目標的有效方法是什么? 請解釋一下,謝謝。

我建議您編寫一個Dao,它返回一個業務對象列表而不是結果集。 必須在Dao本身中關閉連接。 下面是一個例子

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;
}

如果可以使用Java 7,則還可以對資源使用try ,它將自動為您處理連接的關閉。 如果您無法更改Dao界面,則最好在Dao和業務層之間編寫一個層。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM