-1

I am developing a program that uploads data from a MS SQL server to a MySQL server. In IntelliJ the program works without problems. When I export it with Maven to a .jar it comes to the following error:

java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver

my pom.xml:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.14</version>

</dependency>

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>9.4.1.jre8</version>

</dependency>

my DB connection:

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
  • What does that JAR artifact contain exactly? How do you run your JAR file? Did you include proper class path to `java` when running the JAR? Did you try creating an "uber" JAR containing all dependencies in a single JAR so that you could not worry about class path? – terrorrussia-keeps-killing Jan 03 '22 at 11:10

1 Answers1

0

Since you mentioned that your application seems to be working in IntelliJ, but not when a JAR has been created using Maven, it is likely that your JAR does not contain dependencies, but only the classes and code that you created.

There are two ways I usually use to fix this:

  1. Use the maven-shade-plugin to created a shaded (uber) JAR which contains your dependencies as well as your code in a single JAR. You can find more information on the plugin's documentation page: https://maven.apache.org/plugins/maven-shade-plugin/usage.html

  2. Use an explicit classpath when running the JAR. For example, java -cp <YOUR CLASSPATH> your.package.MainClass will run your application with a custom classpath. The <YOUR CLASSPATH> should be replaced with the path including your JAR and dependency JARs. Here is a great answer that describes how to use this method on both Windows and Linux: Using a custom classpath with java. The your.package.MainClass should be replaced by the class name of your main class. There may be other alternatives to this option as well.

Dharman
  • 30,962
  • 25
  • 85
  • 135
NightHowler
  • 167
  • 1
  • 11