0

I have a web APP in tomcat 8 with servlets tecnology. For DB connection I have a servlet listener that keep a static datasource and a static method that do a getConnection. All run fine in the serlvet I can call to servletListener.getConnection();

But inside classes can't call it.

I found this class in internet:

public final class DBUtilClass {
    private static DataSource datasource;

    static {
        Context initContext;
        try {
            initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:/comp/env");
            datasource = (DataSource) envContext.lookup("jdbc/testdb");
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return datasource.getConnection();
    }

I like it because i can call it from all classes. I am not sure if it is the best way.

others aproach? Any recomendations?

mls_dev
  • 511
  • 2
  • 6
  • 21
  • problems arrise when for example two database operations occur is same momment. Or have many dead but not closed Connections. You have part of classic JNDI pattern, but used wrong. Copy JNDI example directylu – Jacek Cz Sep 08 '17 at 14:21
  • thank you, then this pattern fall if we have two operations at the same time? – mls_dev Oct 26 '17 at 08:47
  • Connection cannot be shared between logically independent threads / parts. So static Connection is problem. – Jacek Cz Oct 26 '17 at 09:11
  • thank u, but in my example static method getConnection() create a new connection from static datasource, so the connection is not static. not?? maybe i am lost – mls_dev Nov 06 '17 at 16:16

0 Answers0