Why I can't get the org.h2.Driver? I use maven

joker picture joker · Sep 2, 2015 · Viewed 38.6k times · Source

I face a problem about connecting to H2

this is my pom.xml:

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>.</groupId>
    <artifactId>dbConnection</artifactId>
    <name>Db Connection</name>
    <packaging>war</packaging>
    <version>0.1</version>

    <dependencies>
        <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.3.176</version>
        </dependency>
    </dependencies>


</project>

and this is my main code

import java.sql.*;

public class DbConnection 
{
   static final String DB_URL = "jdbc:h2:tcp://localhost/~/test;AUTO_SERVER=TRUE";

   public static void main(String[] args) throws Exception
   {
        try
           { 
                Class.forName("org.h2.Driver");          
                Connection conn = DriverManager.getConnection(DB_URL,"sa","");  
                conn.close();
           }
       catch(ClassNotFoundException ex)
           {
                System.out.println( "ERROR: Class not found: " + ex.getMessage()); 
           }
    }
}

is always show up that Class not found:org.h2.Driver

Answer

Marko Jurisic picture Marko Jurisic · Dec 10, 2015

You should set scope to runtime so that h2 driver is packaged in your war file:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.190</version>
    <scope>runtime</scope>
</dependency>