Pablochaches
Pablochaches

Reputation: 1068

Maven not including sqlite-jdbc

It seems like maven is not adding sqlite-jdbc-3.36.0.3.jar automatically to my project. Im pretty new to Java, so im not sure what I did wrong.

Minimal example

From the Maven in 5 minutes, create a project:

mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false

In the new project, add:

<dependency>
    <groupId>org.xerial</groupId>
    <artifactId>sqlite-jdbc</artifactId>
    <version>3.36.0.3</version>
</dependency>

To the dependencies, they will look like this:

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.36.0.3</version>
    </dependency>
  </dependencies>

And edit src/main/java/com/mycompany/app/App.java to look like this:

package com.mycompany.app;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class App {
    public static void main(String[] args) {
        // We make sure that we have the driver
        try {
            Class.forName("org.sqlite.JDBC");
        } catch (final ClassNotFoundException e) {
            System.err.println(e);
            return;
        }

        Connection con = null;

        try {
            String connection_string = "jdbc:sqlite:test.db";

            con = DriverManager.getConnection(connection_string);

            System.out.println("It works");
        } catch (final SQLException e) {
            System.err.println(e.getMessage());
        } finally {
            try {
                if (con != null) {
                    con.close();
                }
            } catch (final SQLException e) {
                System.err.println(e.getMessage());
            }
        }
    }
}

Then run:

mvn package

And finally run the project with:

java -cp ./target/my-app-1.0-SNAPSHOT.jar com.mycompany.app.App

And I get the error:

java.lang.ClassNotFoundException: org.sqlite.JDBC

But if I manually add sqlite-jdbc-3.36.0.3.jar, it works correctly.

java -cp ".\target\my-app-1.0-SNAPSHOT.jar;C:\Users\pabsa\.m2\repository\org\xerial\sqlite-jdbc\3.36.0.3\sqlite-jdbc-3.36.0.3.jar" com.mycompany.app.App

What did I did wrong, or why is Maven not adding it automatically?

Upvotes: 2

Views: 2566

Answers (1)

M A
M A

Reputation: 72884

This is expected behavior from Maven: the jar of the application does not include its dependencies by default. Two options:

  1. Either execute the main class using the maven-exec-plugin:

    mvn package exec:java -Dexec.mainClass="com.mycompany.app.App"
    
  2. Or create a jar with its dependencies and execute it instead of the regular jar.

Upvotes: 2

Related Questions