O
O
oberontrik2017-09-24 16:28:45
Java
oberontrik, 2017-09-24 16:28:45

How to properly use the connections to the database received from tomcat'a?

Good afternoon!
I trusted tomcat to make connections to the database.

<resource-ref>
        <res-ref-name>jdbc/TestDB</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
</resource-ref>

As I understand it, tomcat will maintain a pool of connections and give them on request.
But I don't fully understand the "correct" use case.
First, at what point does the connection get received? (2nd or 3rd line?)
InitialContext cxt = new InitialContext();
DataSource ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/TestDB");
Connection сonnection = ds.getConnection();

At what point you need to "take" the connection, and at what time to release it. (And how to release it??)
For example, is it worth taking it when initializing a servlet and giving it away when it is destroyed? Or would it be more correct to take it at the moment the request is received and give it back after it has been processed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2017-09-24
@oberontrik

The DataSource is thread-safe, it can be obtained during initialization and stored in a field. But there is no Connection and it is better to use it within a single method:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try (Connection con = ds.getConnection()) {
        // применяете
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question