Failed to load driver class com.mysql.jdbc.Driver - java

I am trying to run my Spring Boot backend with two profiles, one using H2 in memory database and the second one using MySQL. H2 database works just fine, but when I switch to MySQL I get
APPLICATION FAILED TO START
***************************
Description:
Failed to bind properties under '' to com.zaxxer.hikari.HikariDataSource:
Property: driverclassname
Value: com.mysql.jdbc.Driver;
Origin: "driverClassName" from property source "source"
Reason: Failed to load driver class com.mysql.jdbc.Driver; in either of HikariConfig class loader or Thread context classloader
Action:
Update your application's configuration
I have tried deleting .m2, reimporting, maven clean, compile, install and most of the things I could find on the internet, no success. The funny thing is that I have other project with MySQL database only, I had similar issue, but adding mysql-connector-java dependency solved it. I have no clue right now.
application.properties
spring.profiles.active=#profilename#
#H2 in memory database
domain.datasource.type=H2
domain.datasource.url=jdbc:h2:mem:store;MODE=MYSQL;
domain.datasource.driver-class=org.h2.Driver
domain.datasource.username=sa
domain.datasource.password=
domain.datasource.generate-dll=true
application-local_mysql.properties
spring.profiles.active=#profilename#
#MySQL local database
domain.datasource.type=MYSQL
domain.datasource.url=jdbc:mysql://localhost:3600/store;
domain.datasource.driver-class=com.mysql.jdbc.Driver;
domain.datasource.username=store
domain.datasource.password=store
domain.datasource.generate-dll=false
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sk.personal</groupId>
<artifactId>my-project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>my-project</name>
<description>My personal project.</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>local_h2</id>
<properties>
<profilename>local_h2</profilename>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>local_mysql</id>
<properties>
<profilename>local_mysql</profilename>
<maven.test.skip>true</maven.test.skip>
</properties>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
DatasourceConfig.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import javax.sql.DataSource;
#Configuration
public class DatasourceConfig {
#Value("${domain.datasource.url}")
private String url;
#Value("${domain.datasource.username}")
private String username;
#Value("${domain.datasource.password}")
private String password;
#Value("${domain.datasource.type}")
private String type;
#Value("${domain.datasource.driver-class}")
private String driverClass;
#Bean
public DataSource dataSource() {
if (type.equals("MYSQL")) {
return DataSourceBuilder
.create()
.username(username)
.password(password)
.url(url)
.driverClassName(driverClass)
.build();
} else {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder
.setType(EmbeddedDatabaseType.H2)
.build();
}
}
}

In my case the next dependency was missing:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
In case of using IntelliJ and if you inherit from a <parent>, you can view your effective pom.xml by right clicking anywhere inside your pom.xml, then:
and search for the mysql-connector-java artifact as mentioned.

The answer is so embarrassing. I appended the driver line of application.properties with a semicolon ...
Obviously, it did't recognize that driver.

I had a problem where I was using Spring Boot 2.2.0.RELEASE and needed to connect to an old Mysql DB (5.1.73), which required me to downgrade to mysql-connector-java version 5.1.38
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
Since Spring boot was expecting a newer mysql-java-connector, which has been renamed to com.mysql.cj.jdbc.Driver, I also had to add the spring datasource driver-class-name setting in my spring boot db config.
So my spring boot config ended up like this:
spring:
datasource:
url: 'localhost'
password: password
username: user
driver-class-name: com.mysql.jdbc.Driver

just add mysql and jdbc dependencies like below
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

You don't specify version of MYSQL JDBC driver, so you're likely getting version 8.x, where the driver is named differently than in previous versions:
com.mysql.cj.jdbc.Driver

In my case error throws:
Property: driverclassname
Value: com.mysql.cj.jdbc.Driver
Origin: "driverClassName" from property source "source"
Reason: Failed to load driver class com.mysql.cj.jdbc.Driver in either of HikariConfig class loader or Thread context classloader
So I have just added mysql dependency:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
Try upgrading your driver. Coz Mysql community has updated class name from com.mysql.jdbc.Driver to com.mysql.cj.jdbc. Check More Details

Change the database driver dependency scope to 'runtime'
For example:
<dependency>
<groupId>com.{yourDatabaseGroupid}</groupId>
<artifactId>{yourDatabaseArtifactId}</artifactId>
<scope>runtime</scope>
</dependency>

You should add: spring.datasource.driver-class-name=com.mysql.jdbc.Driver to your application.properties file .
My **application.properties : **
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.datasource.url=jdbc:mysql://localhost:3306/db_name?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root

I cant believe it!
In intellij: Build->rebuild project solved the issue for me!
For more information:
pom.xml:
application.properties:

this issue for me was also caused by the version of mysql.
all i had to do is add the version of mysql in pom.xml dependencies
(in my case the verion is 8.0.25)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
make sure to reload the maven dependecies before your run

I had the same problem as you. For me, it was because of having h2 database dependency!
I don't know how these two can affect each other, but all I did was removing this dependency and now it works just fine!

I my case all configurations were correct but I still get this error.
In Intellij, go in the project structure (ctrl + alt + maj + S) in windows.
Look if u get some problems.
If yes, go on maven in the sidebar: clic on "Generate sources and Update Folders for All projetct"
That resolve my error !

Had to specify the jar path inside project->Properties->JPA-> connection Profile -> JAR List

I had the same issue and the root cause was [ spring.profile.active ]
and the fix is [ spring.profiles.active ] where it is profiles plural
and it was my mistake.

go to https://start.spring.io
In that site:
Dependencies > Search for Mysql drver > select it > Click explore button > copy the latest version of mysql connector > add it into your application.properties file

Related

Failed to bind properties under '' to com.zaxxer.hikari.HikariDataSource: spring boot 2.4.1

I get this output will running me spring app
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to bind properties under '' to com.zaxxer.hikari.HikariDataSource:
Property: driver-class-name
Value: com.mysql.cj.jdbc.Driver
Origin: "driverClassName" from property source "source"
Reason: Failed to load driver class com.mysql.cj.jdbc.Driver in either of HikariConfig class loader or Thread context classloader
Action:
Update your application's configuration
my pom.xml look like this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com</groupId>
<artifactId>couponProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>couponProject-Spring </name>
<description>coupon project part 2 spring</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
and my application.properties looking like this:
spring.datasource.url=jdbc:mysql://localhost:3306/couponproject?serverTimezone=Israel&createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=1234
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
# spring.jpa.properties.hibernate.format_sql=true
# spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
I'm new to spring so I don't really understand why I get this output
I used spring initializer spring JPA
I read similar questions but I couldn't quite understand the solution
Your project is not able to find the jar because maven dependency is missing for MYSQL Drivers . Please add below dependency for mySQL 8 in order to get the drivers available for your application . Add it inside the <dependencies> section of your pom.xml .
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
Or if you want to have another 8.X or 5.X version MySQL based dependency (based upon which version of MySQL it is that you are using) , please use the correct maven dependency from here : https://mvnrepository.com/artifact/mysql/mysql-connector-java .

No session repository could be auto-configured(session store type is 'redis')

I am following the spring security tutorial from this link on that tutorial third part. I have to use redis to hand away session information to resource backend.
Here my applicaiton.yml file:
server:
port: 9000
security:
sessions: NEVER
spring:
session:
store-type: redis
redis:
host: localhost
port: 6379
logging:
level:
org.springframework:
security: DEBUG
session: TRACE
Also, I use HeaderHttpSessionStrategy bean as a session strategy
#Bean
HeaderHttpSessionStrategy sessionStrategy() {
return new HeaderHttpSessionStrategy();
}
My pom couldn't find the related class declaration and give me
package org.springframework.session.web.http does not exist
Above error Here my pom.xml file.
<properties>
<java.version>14</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
I am new in spring and spring-security world. Can any advice solve this problem?
Edit:
After I added the new dependency in pom
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
I solve the above problem but this time hit me the new one it says:
No session repository could be auto-configured, check your configuration (session store type is 'redis'
My redis configuration on application.yml is above. And I am using redis on docker. My docker yml is:
redis:
image: redis
ports:
- "6379:6379"
I got this error recently. I was using Spring Boot 2.4.0. I had added the dependency for Spring Session, but forgot to add one for Jedis.
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
When I first deployed, with that it gave me the message:
No session repository could be auto-configured, check your configuration (session store type is 'redis')
After I added this dependency and rebuilt my JAR, everything worked.
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
Perhaps that will help someone else.

Failed to bind properties under " to com.zaxxer.hikari.HikariDataSource:" Springboot

I have already added ojdbc ddriver and included the dependency in pom, but I still get the error mentioned in the title. Please help.
Earlier I ran the application with a local postgres db. Now trying to connect to a remote oracle db, and encountered this problem. I am logged into the necessary firewalls.
The appplication started and performed as exected with the postgresdb.
I get the following logs when trying to start my application now -
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-03-06 12:08:51.786 ERROR 27236 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to bind properties under '' to com.zaxxer.hikari.HikariDataSource:
Property: driverclassname
Value: oracle.jdbc.OracleDriver
Origin: "driverClassName" from property source "source"
Reason: Failed to load driver class oracle.jdbc.OracleDriver in either of HikariConfig class loader or Thread context classloader
Action:
Update your application's configuration
Process finished with exit code 1
The pom file is as below
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>package</groupId>
<artifactId>QualityScore</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>QualityScore</name>
<description>Demo project in Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>12.2.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application.properties -
##Postgres settings
##spring.datasource.url=jdbc:postgresql:*****
##spring.datasource.username=*****
##spring.datasource.password=*****
##spring.jpa.database-platform = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto = none
spring.jpa.hibernate.show-sql=true
# Oracle settings
spring.datasource.url=jdbc:oracle:*****
spring.datasource.username=*****
spring.datasource.password=*****
spring.datasource.driver-class=oracle.jdbc.driver.OracleDriver
# HikariCP settings
spring.datasource.hikari.connection-timeout=60000
spring.datasource.hikari.maximum-pool-size=5
#spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
I got the solution or fix.
I added the following property in application.properties
spring.datasource.driver-class=oracle.jdbc.driver.OracleDriver
and explicitly specified the driver(ojdbc8) in the modules of the project structure.
Now it works!!! Thank you everyone for your help!!
you application.properties is wrong. You have:
#spring.datasource.url=jdbc:*****
#spring.datasource.username=****
#spring.tasource.password=*****
#spring.jpa.database-platform = *****
spring.jpa.hibernate.ddl-auto = none
spring.jpa.hibernate.show-sql=true
spring.datasource.url=jdbc:oracle:****
spring.datasource.username=*****
spring.datasource.password=*****
#spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
Recipientlist=*****
but you don't have your driver-class-name set. should be:
#spring.datasource.url=jdbc:*****
#spring.datasource.username=****
#spring.tasource.password=*****
#spring.jpa.database-platform = *****
spring.jpa.hibernate.ddl-auto = none
spring.jpa.hibernate.show-sql=true
spring.datasource.url=jdbc:oracle:****
spring.datasource.username=*****
spring.datasource.password=*****
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
#spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
Recipientlist=*****
Regards!
In my controller test classes, this error occurred when running the tests. Even with the spring.datasource.driver-class-name property set.
To resolve this, we added the DataSouce attribute with the #MockBean annotation in the controller test classes:
#MockBean
private DataSource dataSource;
The test classes performed perfectly.

H2-In memory database console not opening

I am using the H2 database in a Spring boot application. But unable to open it in the browser at http://localhost:8080/console. My pom.xml is as below:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.192</version>
</dependency>
Spring boot Configuration :
Springboot configuration file
#Configuration
public class WebConfiguration {
#Bean
ServletRegistrationBean h2servletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
registrationBean.addUrlMappings("/console/*");
return registrationBean;
}
}
to use the H2 console you need to configure it in your .properties file
spring.h2.console.enabled=true
spring.h2.console.path=/h2console/
where /h2console/ is the path you want to use on the browser so you can change it to anything. Also if you have security enabled you might want to add it to the permitted paths
also add this to your HttpSecurity configuration http.headers().frameOptions().disable();
Edit
change your security configuration i'm pretty sure you might have spring security in your pom so use this instead, if not it should work
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
public class WebConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests().antMatchers("/").permitAll().and()
.authorizeRequests().antMatchers("/console/**").permitAll();
httpSecurity.csrf().disable();
httpSecurity.headers().frameOptions().disable();
}
}
If have included spring-boot-starter-security artifact in your pom then by default basic authentication is enabled. Hence, to access your console either you disable the basic authentication by adding security.basic.enabled=false in your application.properties or allow the access in your configure method as below:
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().authorizeRequests().antMatchers("/").permitAll().and().authorizeRequests()
.antMatchers("/console/**").permitAll();
httpSecurity.headers().frameOptions().disable();
}
}
Thank you all for your generous help.The application class (Springboot) was in a separate package and it was not scanning other packages.Also I modified my Pom.xml a bit which finally helped me to access the console.Attached is my new Pom.xml.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.spring.app</groupId>
<artifactId>Demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBootApp</name>
<description>Generator of statistics </description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--WebJars -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.4</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring AOP + AspectJ -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<!-- JavaConfig need this library -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<!-- Jackson JSON Mapper -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
go the POM file and add the dependency :
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
rebuild your project
this might help folks , all the configuration above is correct
Note - if you are not using any security then adding spring security is not required
Actualy problem is - when you open this url in chrome
http://localhost:8080/h2 chrome makes it --> https://localhost:8080/h2
To get rid of this issue - Below reference will help -
Google Chrome redirecting localhost to https
You might have face 2 situation including following errors:
localhost refused to connect
Double check the URL. Chrome automatically try to change http:// to https://
Check spring.h2.console.path (Path at witch the console avilible) to get your URL:
Default: /h2-console --> URL: http://localhost:8080/h2-console/
If you running IDE (e.g. IntelliJ Idea), make sure your app is running witch means your H2 data base is running!
You face 404 Error:
In this case your H2 Data base is correctly running on Port 8080 and you already have the connection with it.
Check spring.h2.console.path (Path at witch the console avilible) to get your URL:
Default: /h2-console --> URL: http://localhost:8080/h2-console/
Enable H2 Console
spring.h2.console.enabled=true
The issue might be also be caused by adding server.servlet.context-path to properties. The new url will be composed of server.servlet.context-path plus spring.h2.console.path
If you have renamed the h2 path in the application.properties to "console" you've to add it in your antMatcher like .antMatcher("/console/**") with two asterisks after the "console" because there are much more appendings.
If none of the above solution works, try below one, this worked for me :
Add below property in your application.propertiesfollowing
spring.data.jpa.repositories.bootstrap-mode=default
Open console in browser using this URL : http://localhost:8080/h2-console
On a login page make sure that you use jdbc:h2:mem:testdb as JDBC URL.
As h2 database console is mapped to "h2-console".
Use this:
http.csrf().disable().authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.anyRequest().authenticated();
// disable frame options
http.headers().frameOptions().disable();
`
You don't need permit root access:
.antMatchers("/") * NOT NEEDED *

How to create a simple CRUD application using Spring Data JPA and MYSQas DB using SpringBoot?

I'm trying to create a simple dummy application using Spring Boot Version 1.4.4.
Here is how my pom.xml looks like :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bootstrap</groupId>
<artifactId>bootstrap</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>tsqln</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
My application class looks like:
package com.bootstrap;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class TsqlnApplication {
public static void main(String[] args) {
SpringApplication.run(TsqlnApplication.class, args);
}
}
And my application.properties looks like :
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/lostandfound
spring.datasource.username=root
spring.datasource.password=root
But when I run the application I get the following error stating :
*****************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration required a bean of type 'javax.sql.DataSource' that could not be found.
- Bean method 'dataSource' not loaded because #ConditionalOnClass did not find required class 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType'
- Bean method 'dataSource' not loaded because #ConditionalOnClass did not find required class 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType'
Action:
Consider revisiting the conditions above or defining a bean of type 'javax.sql.DataSource' in your configuration.
2017-01-29 17:32:44.645 ERROR 4316 --- [ main] o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener#516be40f] to prepare test instance [com.bootstrap.TsqlnApplicationTests#9573b3b]**
My directory structure for project is :
However with the same approach the above application works with SpringBoot version 1.3. Any suggestions how to make it work with version 1.4.4?
in your application.properties add this lines
spring.datasource.url = jdbc:mysql://localhost:3306/yourdatabase
# Username and password
spring.datasource.username = root
spring.datasource.password =
# Show or not log for each sql query
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = create
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Make sure your mysql-connector is actually there in the classpath at runtime (if your using Tomcat, then it should be in the lib folder).
If you do not have it there add a compile dependency in your pom.xml
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
Also you forgot about this line in your application.properties:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
You can restore that behaviour by creating your own datasource bean:
#Bean
public DataSource dataSource() {
return DataSourceBuilder
.create()
.username("")
.password("")
.url("")
.driverClassName("")
.build();
}

Categories

Resources