Saturday, April 15, 2023

How to fix cannot determine embedded database driver class for database type NONE

Hello and welcome to the blog post. Today we are going to take a look at a frequently encountered problem in Spring Boot Application. If you are reading this, I'm going to assume that you saw the problem "Cannot determine embedded database driver class for database type NONE" while executing a Spring Boot application. We will understand, when this error appears. For this we will create a simple Spring Boot project as shown below. It demonstrates how I encountered the problem "Cannot determine embedded database driver class for database type NONE".  


How to fix cannot determine embedded database driver class for database type NONE

Below is the project structure


├── java

│   └── com

│       └── practice

│           └── springboot

│               ├── controller

│               │   └── EmployeeController.java

│               ├── entity

│               │   └── Employee.java

│               ├── repo

│               │   └── EmployeeRepo.java

│               ├── service

│               └── SpringBootPracticeApplication.java

└── resources

    ├── application.properties

    ├── static

└── templates


Employee.java

package com.practice.springboot.entity;



import jakarta.persistence.*;



@Entity

@Table(name = "employees")

public class Employee {

    @Id

    @GeneratedValue(strategy = GenerationType.AUTO)

    private int id;

    private String name;

    private int age;

    private double salary;

    private String qualification;



    public int getId() {

        return id;

    }



    public void setId(int id) {

        this.id = id;

    }



    public String getName() {

        return name;

    }



    public void setName(String name) {

        this.name = name;

    }



    public int getAge() {

        return age;

    }



    public void setAge(int age) {

        this.age = age;

    }



    public double getSalary() {

        return salary;

    }



    public void setSalary(double salary) {

        this.salary = salary;

    }



    public String getQualification() {

        return qualification;

    }



    public void setQualification(String qualification) {

        this.qualification = qualification;

    }

}



EmployeeRepo.java



package com.practice.springboot.repo;



import com.practice.springboot.entity.Employee;

import org.springframework.data.jpa.repository.JpaRepository;



public interface EmployeeRepo extends JpaRepository<Employee,Integer> {

}



EmployeeController.java


package com.practice.springboot.controller;



import com.practice.springboot.repo.EmployeeRepo;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;



@RestController

@RequestMapping("/api/v1")

public class EmployeeController {



    @Autowired

    EmployeeRepo employeeRepo;



    @RequestMapping("/employees")

    public ResponseEntity<?> getEmployees(){

        return new ResponseEntity<>(employeeRepo.findAll(), HttpStatus.OK);

    }

}




SpringBootPracticeApplication.java


package com.practice.springboot;



import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;



@SpringBootApplication

public class SpringBootPracticeApplication {



   public static void main(String[] args) {

      SpringApplication.run(SpringBootPracticeApplication.class, args);

   }



}


When I run the SpringBootPracticeApplication.java, it produces the following error in the console.

***************************

APPLICATION FAILED TO START

***************************


Description:

Cannot determine embedded database driver class for database type NONE


Action:

If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

  .   ____          _            __ _ _

 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )

  '  |____| .__|_| |_|_| |_\__, | / / / /

 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::        (v1.5.1.RELEASE)


********************************************************************************************

Or you may find an error like the one given below

********************************************************************************************


Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.

2023-03-07T20:10:04.859+05:00 ERROR 12394 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 


***************************

APPLICATION FAILED TO START

***************************


How to fix cannot determine embedded database driver class for database type NONE


Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.


Reason: Failed to determine a suitable driver class

Action:

Consider the following:

If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.

If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).



Why this error?

This error occurs when your spring boot application's DataSource is not setup. This error message is thrown when there is no configuration supplied for the DataSource while the spring boot program is running and tries to setup the DataSource.

<dependency>

   <groupId>org.springframework.boot</groupId>

   <artifactId>spring-boot-starter-data-jpa</artifactId>

   <version>3.0.4</version>

</dependency>



<dependency>

   <groupId>mysql</groupId>

   <artifactId>mysql-connector-java</artifactId>

   <version>8.0.32</version>

</dependency>


As you can see we have defined spring-starter-data-jpa and mysql database dependency in our project. The auto-configuration feature of Spring Boot tries to setup the beans automatically using the classpath dependencies. The issue is that we haven't provided Spring with the details it needs in order to carry out the auto-configuration process.

When working with external databases like MySQL, PostgreSQL, Oracle, and MSSQL, for instance, we'll need to declare the JDBC connection attributes that we've omitted from the definition so far. Otherwise, you can use an in-memory database, since in-memory databases like H2 can construct a data source without all of this information, we won't have this problem with them.


How to fix this?

There are a couple of ways to fix this issue, let’s see a few of these in our article.  

Exclude auto-configuration of DataSource.

Adding required properties to application.properties file.

Add dependencies to your pom.xml file


Exclude data-source auto-configuration

Excluding the auto-config data source can fix this issue. We can achieve it using the following approaches.

Part of SpringBootApplication annotation itself


@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })

public class SpringBootPracticeApplication {



   public static void main(String[] args) {

      SpringApplication.run(SpringBootPracticeApplication.class, args);

   }

}


By adding EnableAutoConfiguration annotation


@SpringBootApplication

@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class })

public class SpringBootPracticeApplication {



   public static void main(String[] args) {

      SpringApplication.run(SpringBootPracticeApplication.class, args);

   }

}


Disable auto-configuration in our application.properties file 


spring.autoconfigure.exclude=

org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration



Adding required properties to application.properties

Define datasource properties in the application.properties file


spring.jpa.hibernate.ddl-auto=create

spring.jpa.show-sql=true

spring.datasource.username=user

spring.datasource.password=password

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/dBName?useSSL=false

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect



Programmatically define DataSource


@Configuration

public class DataSourceConfig {

    @Bean

    public DataSource getDataSource() {

        return DataSourceBuilder.create()

          .driverClassName("com.mysql.cj.jdbc.Driver")

          .url("jdbc:mysql://localhost:3306/dBName")

          .username("user")

          .password("password")

          .build();	

    }

}


Adding dependencies in pom.xml / build.gradle

If you want to use an embedded database, then you can add spring boot starter H2 dependency to your pom.xml or build.gradle file.


<dependency>

   <groupId>com.h2database</groupId>

   <artifactId>h2</artifactId>

   <version>2.1.214</version>

   <scope>test</scope>

</dependency>

It is to note here that, the H2 embedded database keeps the data in memory and doesn’t store it permanently. Therefore you can’t access the data after the application’s life cycle.



Conclusion

That's all about How to fix cannot determine embedded database driver class for database type NONE in Spring Boot application. We have now come to the conclusion of this brief article. It tries to assist you in resolving "Cannot determine embedded database driver class for database type NONE". This essay has shown us three distinct ways to solve this problem. I really hope you find this information to be useful.


No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.