Search code examples
javamavenjdbcapache-tomee

is tomEE aware of maven dependency?


I am trying to use postgresql driver with tomcat. but when i run tomcat I am getting FileNotFound exception(Class.forName("org.postgresql.Driver")). Is tomEE aware of maven dependency. how can I overcome it


Solution

  • No. Maven not involved after Tomcat/TomEE deployment

    No, TomEE does not know about Maven or your POM.

    As commented by Andreas, your Maven-driven web-app project will produce a WAR file or EAR file. That file contains any dependencies you may have configured in your POM.

    For deployment, you will be moving that WAR or EAR file to the TomEE server. At that point there is no more Maven involvement.

    These comments above apply to your eventual deployment for production. While in development, you may be using an IDE such as IntelliJ/NetBeans/Eclipse that can call upon an external web container such as Tomcat or TomEE to run and debug your web app. Maven settings may be involved in that special case, as part of hooking up your IDE to the external web container. Even in this special case, Tomcat/TomEE is not aware of Maven having possibly participated in its launching or configuration.

    JDBC drivers are special

    Furthermore, deploying a JDBC driver to Tomcat, TomEE, or other Jakarta Servlet container is a complicated matter because of classloader issues and the JDBC driver registration process. Generally, you should not be bundling a JDBC driver within your WAR/EAR.

    Search Stack Overflow to learn more. Remember that TomEE is built on Apache Tomcat, so most anything you read about Tomcat applies.

    See:

    By the way, in modern Java with its JDBC driver registration feature (DriverManager), you no longer need to call Class.forName. That call is now legacy.

    DataSource

    Tip: Learn to use a DataSource implementation provided by your driver. Regarding Postgres, if using the JDBC driver from jdbc.postgresql.org, see this chapter.

    PGSimpleDataSource pgDataSource = new PGSimpleDataSource();
    pgDataSource.setDataSourceName("Acme Corp invoicing database");
    pgDataSource.setServerName("localhost");
    pgDataSource.setDatabaseName("test");
    pgDataSource.setUser("testuser");
    pgDataSource.setPassword("testpassword");
    
    DataSource dataSource = pgDataSource ;  // Perhaps save as an "attribute" on your web app's "context". 
    

    Ask the data source for a Connection object when needing to talk to the database. Usually best to use try-with-resources syntax.

    try 
    (
        Connection conn = dataSource.getConnection() ;
    ) 
    {
        … do your database work
    }
    

    Later you can learn to configure this DataSource info externally, outside your code base. That configuration is done through JNDI and a naming server such as the LDAP-style server built into Tomcat.