2

I am working on a Java project where we want to use an embedded database using JDBC for connection and Derby as the database. This is a maven project which deploys to an executable JAR.

I have included Derby as a dependency on the project. I am using Java 1.8, Maven 3.8.0, and Derby 10.8.3.0.

POM.xml

<!-- Derby for database connection -->
<dependency>
  <groupId>org.apache.derby</groupId>
  <artifactId>derby</artifactId>
  <version>10.8.3.0</version>
</dependency>

App.java

public class App {

public static void main(String[] args) {
    JOptionPane.showMessageDialog(null, "Hello World.");


    SampleDB sdb = new SampleDB();
    try {
        sdb.connectionToDerby();
        sdb.sampleDBUsabe();
    } catch (SQLException sqle) {
        System.out.println(sqle);
    }
}
}

SampleDB.java

public class SampleDB {
private Connection conn;

public void connectionToDerby() throws SQLException {
    String dbURL = "jdbc:derby:sampledb;create=true";
    conn = DriverManager.getConnection(dbURL);
}

public void sampleDBUsabe() throws SQLException {
    Statement stmt = conn.createStatement();

    //Create Table
    stmt.execute("Create Table USERS (id int primary key, name varchar(30))");
...
}

When I execute the generated .JAR file I get the error:

$ java -jar target/puzzle.game-0.0.1-SNAPSHOT.jar
java.sql.SQLException: No suitable driver found for jdbc:derby:sampledb;create=true

I suspect this is due to the Derby driver not being a part of my class path. Is there a way to do this using maven or a settings.xml file so that this happens automatically when a user runs the mvn install goal?

Clifford
  • 88,407
  • 13
  • 85
  • 165
KyleAure
  • 465
  • 4
  • 15
  • Yes, your problem is a CLASSPATH problem. And yes, derby.jar is designed to be embedded into your application. By the way, Derby 10.8 is VERY old. Please consider switching to Derby 10.14, which is much newer. – Bryan Pendleton Feb 16 '19 at 18:59

2 Answers2

1

When you start your application, you will need derby-10.8.3.0.jar in your classpath.

java -cp derby-10.8.3.0.jar;target/puzzle.game-0.0.1-SNAPSHOT.jar App

The classpath delimiter is OS dependent. You may have to adjust that.

As mentioned by Bryan Pendleton, you should use a current Derby release.

<dependency>
  <groupId>org.apache.derby</groupId>
  <artifactId>derby</artifactId>
  <version>10.14.2.0</version>
</dependency>
Jens Dibbern
  • 1,434
  • 2
  • 13
  • 20
1

See an answer to this question: Building a fat jar using maven . You need to use the maven assembly plugin in order to create a so called fat/uber jar.

Maxim Kirilov
  • 2,639
  • 24
  • 49