Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Yes, it is possible. For this case where you want that each Thread has its own Connection, you need to use <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html" rel="nofollow">ThreadLocal</a>, since each request spawn its own Thread. You just need to make sure to close the connection at the end of the request, this is achieved using a <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/Filter.html" rel="nofollow">Filter</a>.</p> <p>The filter should be before any other Filter to ensure that the connection is closed at the end of the request.</p> <p>DBUtil:</p> <pre><code>public class DBUtil { private static ThreadLocal&lt;Connection&gt; connectionHolder = new ThreadLocal&lt;Connection&gt;(); public static Connection getConnection() { Connection connection = connectionHolder.get(); if (connection == null) { //open the connection (lazy loaded) //store it connectionHolder.set(connection); } return connectionHolder.get(); } public static void close() { Connection connection = connectionHolder.get(); if (connection != null) { //close the connection //remove it from the connection holder connectionHolder.remove(); } } } </code></pre> <p><strong>DBFilter</strong>:</p> <pre><code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { chain.doFilter(request, response); } finally { DBUtil.close(); } } </code></pre> <p>It is better if you use a framework for these kind of things, for example <a href="http://projects.spring.io/spring-framework/" rel="nofollow">Spring Framework</a> already do this by proxying your services and it handles the connection and transaction also gives you a lot of other features.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload