Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy - class not found

The following Groovy script fails with a java.lang.ClassNotFoundException: com.mysql.jdbc.Driver exception.

@Grapes([
    @Grab('mysql:mysql-connector-java:5.1.25')
])

import groovy.sql.Sql

def sql = Sql.newInstance(
    'jdbc:mysql://localhost/books', 
    'root',
    '', 
    'com.mysql.jdbc.Driver'
);

I looked into the JAR file stored at C:\Users\Dusan\.groovy\grapes\mysql\mysql-connector-java\jars\mysql-connector-java-5.1.25.jar and it contains the Driver class.

What can be wrong?

like image 888
Dušan Rychnovský Avatar asked Aug 03 '13 18:08

Dušan Rychnovský


People also ask

Why I AM getting class Not found exception?

ClassNotFoundException in Java? ClassNotFoundException is a checked exception and occurs when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath. In older days, there are no editors like Eclipse are available.

How do you fix No class Def Found error?

lang. NoClassDefFoundError, which means the Class Loader file responsible for dynamically loading classes can not find the . class file. So to remove this error, you should set your classpath to the location where your Class Loader is present.


2 Answers

You need:

@GrabConfig(systemClassLoader = true)

After your @Grab, and just:

@Grab('mysql:mysql-connector-java:5.1.25')
@GrabConfig(systemClassLoader = true)
import groovy.sql.Sql

def sql = Sql.newInstance(
    'jdbc:mysql://localhost/books', 
    'root',
    '', 
    'com.mysql.jdbc.Driver'
)

Should do

like image 60
tim_yates Avatar answered Oct 02 '22 14:10

tim_yates


How do you use it in groovysh ?

As per the doc, Grab is used in the shell this way

groovy.grape.Grape.grab([group:'mysql:mysql-connector-java:5.1.25'])

I haven't found the equivalent for @GrabConfig. It simply does not work inside groovysh.

like image 39
Francois Lacoursiere Avatar answered Oct 02 '22 14:10

Francois Lacoursiere