Category Archives: Spring

[Solved] java.lang.ClassNotFoundException: org.hsqldb.jdbcDriver


JDBC or Springboot or hibernate throw this exception when you mentioned driver as org.hsqldb.jdbcDriver in your JDBC code or XML configuration or data source configuration properties file but required database driver jar or dependencies is not added in class path.

This exception occurs by below methods :

  • The forName method in the class Class.

                 Class.forName(java.lang.String)

  • The findSystemClass method in the class ClassLoader.

                ClassLoader.findSystemClass()

  • The loadClass method in class ClassLoader.

                ClassLoader.loadClass(java.lang.String, boolean)

java.lang.ClassNotFoundException is Checked Exception which is subclass of  java.lang.ReflectiveOperationException. This  is thrown when application load a class by String name whose definition is not found.

Constructors

  • ClassNotFoundException(): Constructs a ClassNotFoundException with no detail message.
  • ClassNotFoundException(String s) : Constructs a ClassNotFoundException with the specified detail message.
  • ClassNotFoundException(String s, Throwable ex) : Constructs a ClassNotFoundException with the specified detail message and optional exception that was raised while loading the class.

 Difference between Class.forName() and ClassLoader.loadClass()

Example 1: ClassNotFoundException

Below is example of connecting with database and retrieve data from sql table. This will throw ClassNotFoundException because sql driver jar is not in classpath. After this example also mentioned solution.

package example;

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

public class ClassNotFoundException1 {

	public static void main(String[] args) {
		try {
			Class.forName("<strong>org.hsqldb.jdbcDriver</strong>");

			Connection con = DriverManager.getConnection("jdbc:hsqldb:hsql//localhost:3306/FacingIssuesOnITDB", "root", "");

			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("select name from employee");
			String dbtime;
			while (rs.next()) {
				dbtime = rs.getString(1);
				System.out.println(dbtime);
			}

			con.close();

		} catch (ClassNotFoundException | SQLException e) {
			System.out.println("Connection Failed! Check output console");
			e.printStackTrace();
		}

	}

}

Output:

Connection Failed! Check output console
<pre><code>
<strong>java.lang.ClassNotFoundException: org.hsqldb.jdbcDriver</strong>
	at java.net.URLClassLoader.findClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at org.springframework.util.ClassUtils.forName(ClassUtils.java:251)
	at org.springframework.jdbc.datasource.embedded.HsqlEmbeddedDatabaseConfigurer.getInstance(HsqlEmbeddedDatabaseConfigurer.java:48)
	at org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseConfigurerFactory.getConfigurer(EmbeddedDatabaseConfigurerFactory.java:43)
	... 54 common frames omitted
</code></pre>

Solutions:

For solving ClassNotFoundException by Class.ForName() method  considering above example to load MySQL driver same way you can follow for other classes and different DB drivers.

Solution in Eclipse :Follow below steps :

  • Right click your project folder and open up Properties.
  • From the right panel, select Java Build Path then go to Libraries tab.
  • Select Add External JARs to import the HSQLDB driver.
  • From the right panel, select Deployment Assembly.
  • Select Add…, then select Java Build Path Entries and click Next.
  • You should see the SQL driver on the list. Select it and click first.

Tomcat :

If directly running from tomcat. Just copy the HSQL-Connector.jar into Tomcat’s lib folder/directory, and then remove the jar from the webApp’s lib folder, and then, run the project.

Maven Springboot application

Add below dependency in your pom.xml file


<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
</dependency>

Summary :

  • Define what is ClassNotFoundException.
  • What are methods throws ClassNotFoundException?
  • Example for ClassNotFoundException.
  • How to fix ClassNotFoundException in Eclipse and Tomcat.
  • How to fix Springboot maven applications.
Advertisements

[Solved] java.lang.ClassCastException: org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext


ClassCastException throws in code has attempted to cast an object to a subclass of which it is not an instance.

  • ClassCastException(): Constructs a ClassCastException with no detail message.
  • ClassCastException( String s): Constructs a ClassCastException with specified detail message.

Exception Stack Trace

Caused by: java.lang.ClassCastException: org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext
    at org.apache.logging.log4j.core.LoggerContext.getContext(LoggerContext.java:190) ~[log4j-core-2.10.0.jar:2.10.0]
    at org.apache.logging.log4j.core.config.Configurator.setLevel(Configurator.java:291) ~[log4j-core-2.10.0.jar:2.10.0]
    at org.elasticsearch.common.logging.Loggers.setLevel(Loggers.java:149) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.common.logging.Loggers.setLevel(Loggers.java:144) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.index.SearchSlowLog.setLevel(SearchSlowLog.java:111) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.index.SearchSlowLog.(SearchSlowLog.java:106) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.index.IndexModule.(IndexModule.java:127) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.indices.IndicesService.createIndexService(IndicesService.java:440) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.indices.IndicesService.createIndex(IndicesService.java:413) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.cluster.metadata.MetaDataCreateIndexService$1.execute(MetaDataCreateIndexService.java:378) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.cluster.ClusterStateUpdateTask.execute(ClusterStateUpdateTask.java:45) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.cluster.service.ClusterService.executeTasks(ClusterService.java:634) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.cluster.service.ClusterService.calculateTaskOutputs(ClusterService.java:612) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.cluster.service.ClusterService.runTasks(ClusterService.java:571) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.cluster.service.ClusterService$ClusterServiceTaskBatcher.run(ClusterService.java:263) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.cluster.service.TaskBatcher.runIfNotProcessed(TaskBatcher.java:150) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.cluster.service.TaskBatcher$BatchedTask.run(TaskBatcher.java:188) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:575) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.runAndClean(PrioritizedEsThreadPoolExecutor.java:247) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.run(PrioritizedEsThreadPoolExecutor.java:210) ~[elasticsearch-5.6.10.jar:5.6.10]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) ~[na:1.8.0_151]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) ~[na:1.8.0_151]
    at java.lang.Thread.run(Unknown Source) ~[na:1.8.0_151]

Issue

This exception “org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext” occurs because project build with maven and contains spring-boot-starter-web which imports the dependency because we can’t skip with spring-boot-starter-web and need log4j.

Solutions 1

Solution to get log4j with web project is to exclude log4j-to-slf4 from class path as given below:


    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
    <exclusion>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-to-slf4j</artifactId>
    </exclusion>
    </exclusions>
</dependency>

Solutions 2

If you are using simple Spring boot console based application or any Spring template and interfacing with this exception.


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
<version>2.0.2</version>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j;</artifactId>
<version>2.0.2-sources;</version>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl;</artifactId>
<version>2.0.2;</version>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl;</artifactId>
<version>2.0.2-sources;</version>
</dependency>

More Issues Solution

For more other JAVA/JDBC issues solution follow link JAVA/JDBC Issues.

[Solved] JDBC, “Invalid argument value: java.io.NotSerializableException; nested exception is java.sql.SQLException”


JDBC “java.io.NotSerializableException” occurs while using Spring JDBC Template for connectivity and passing arguments for searching/update as parameters. Because JDBC parameters always required searialize objects.

Mostly happen when forget to use get fields value from object and class is not serializable.

Example :

Exception Message

Invalid argument value: java.io.NotSerializableException; nested exception is java.sql.SQLException: Invalid argument value: java.io.NotSerializableException

Class using

public class DynamicDashboard {
private int dashboardId;
private String dashboardName;
private String htmlContent;
private String scriptContent;
private String ruleContent;

public DynamicDashboard()
{
	super();
}

//Getter and Setters

Below is my DAO class method where this exception occured  for column RULE_CONTENT.

public void addDashboard(DynamicDashboard dynamicDashboard) {
		String sql = "INSERT INTO dynamic_dashboard "
				+ "(DASHBOARD_NAME, HTML_CONTENT,SCRIPT_CONTENT,RULE_CONTENT) VALUES (?, ?, ?,?)";

		try {
			jdbcTemplate = new JdbcTemplate(dataSource);

			jdbcTemplate.update(sql,
					new Object[] { dynamicDashboard.getDashboardName(), dynamicDashboard.getHtmlContent(),
							dynamicDashboard.getScriptContent(), dynamicDashboard});
		} catch (Exception ex) {
			logger.error(ex.getMessage());
		}

	}

In above method we forget to get last parameter value for rule like dynamicDashboard.getRuleContent()for database column RULE_CONTENT because JDBCTemplate always required serializable object and all wrapper classes(Integer, String etc.) are searializable. It will through exception “java.io.NotSerializableException” as above.

Solution :

Add get method for ruleContent for object dynamicDashboard.

Correct Code

public void addDashboard(DynamicDashboard dynamicDashboard) {
		String sql = "INSERT INTO dynamic_dashboard "
				+ "(DASHBOARD_NAME, HTML_CONTENT,SCRIPT_CONTENT,RULE_CONTENT) VALUES (?, ?, ?,?)";

		try {
			jdbcTemplate = new JdbcTemplate(dataSource);

			jdbcTemplate.update(sql,
					new Object[] { dynamicDashboard.getDashboardName(), dynamicDashboard.getHtmlContent(),
							dynamicDashboard.getScriptContent(), dynamicDashboard.getRuleContent()});
		} catch (Exception ex) {
			logger.error(ex.getMessage());
		}

	}

More Issues

For more JDBC issue solution follow link Common JDBC Issues.

Leave you feedback to enhance more on this topic so that make it more helpful for others.